xref: /titanic_51/usr/src/cmd/cmd-inet/sbin/dhcpagent/agent.c (revision 42a7bded1b1244af097afdc88654381a3d3879f9)
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 &&
945 		    iu_schedule_timer_ms(tq, lrand48() % DHCP_SELECT_WAIT,
946 		    dhcp_start, dsmp) != -1) {
947 			hold_smach(dsmp);
948 			/* next destination: dhcp_start() */
949 			break;
950 		}
951 
952 		dhcp_selecting(dsmp);
953 		/* next destination: dhcp_requesting() */
954 		break;
955 	}
956 
957 	case DHCP_STATUS: {
958 		dhcp_status_t	status;
959 		dhcp_lease_t	*dlp;
960 
961 		status.if_began = monosec_to_time(dsmp->dsm_curstart_monosec);
962 
963 		/*
964 		 * We return information on just the first lease as being
965 		 * representative of the lot.  A better status mechanism is
966 		 * needed.
967 		 */
968 		dlp = dsmp->dsm_leases;
969 
970 		if (dlp == NULL ||
971 		    dlp->dl_lifs->lif_expire.dt_start == DHCP_PERM) {
972 			status.if_t1	= DHCP_PERM;
973 			status.if_t2	= DHCP_PERM;
974 			status.if_lease	= DHCP_PERM;
975 		} else {
976 			status.if_t1	= status.if_began +
977 			    dlp->dl_t1.dt_start;
978 			status.if_t2	= status.if_began +
979 			    dlp->dl_t2.dt_start;
980 			status.if_lease	= status.if_began +
981 			    dlp->dl_lifs->lif_expire.dt_start;
982 		}
983 
984 		status.version		= DHCP_STATUS_VER;
985 		status.if_state		= dsmp->dsm_state;
986 		status.if_dflags	= dsmp->dsm_dflags;
987 		status.if_sent		= dsmp->dsm_sent;
988 		status.if_recv		= dsmp->dsm_received;
989 		status.if_bad_offers	= dsmp->dsm_bad_offers;
990 
991 		(void) strlcpy(status.if_name, dsmp->dsm_name, IFNAMSIZ);
992 
993 		send_data_reply(iap, 0, DHCP_TYPE_STATUS, &status,
994 		    sizeof (dhcp_status_t));
995 		break;
996 	}
997 	}
998 }
999 
1000 /*
1001  * check_rtm_addr(): determine if routing socket message matches interface
1002  *		     address
1003  *
1004  *   input: const struct if_msghdr *: pointer to routing socket message
1005  *	    int: routing socket message length
1006  *	    boolean_t: set to B_TRUE if IPv6
1007  *	    const in6_addr_t *: pointer to IP address
1008  *  output: boolean_t: B_TRUE if address is a match
1009  */
1010 
1011 static boolean_t
1012 check_rtm_addr(const struct ifa_msghdr *ifam, int msglen, boolean_t isv6,
1013     const in6_addr_t *addr)
1014 {
1015 	const char *cp, *lim;
1016 	uint_t flag;
1017 	const struct sockaddr *sa;
1018 
1019 	if (!(ifam->ifam_addrs & RTA_IFA))
1020 		return (B_FALSE);
1021 
1022 	cp = (const char *)(ifam + 1);
1023 	lim = (const char *)ifam + msglen;
1024 	for (flag = 1; flag < RTA_IFA; flag <<= 1) {
1025 		if (ifam->ifam_addrs & flag) {
1026 			/* LINTED: alignment */
1027 			sa = (const struct sockaddr *)cp;
1028 			if ((const char *)(sa + 1) > lim)
1029 				return (B_FALSE);
1030 			switch (sa->sa_family) {
1031 			case AF_INET:
1032 				cp += sizeof (struct sockaddr_in);
1033 				break;
1034 			case AF_LINK:
1035 				cp += sizeof (struct sockaddr_dl);
1036 				break;
1037 			case AF_INET6:
1038 				cp += sizeof (struct sockaddr_in6);
1039 				break;
1040 			default:
1041 				cp += sizeof (struct sockaddr);
1042 				break;
1043 			}
1044 		}
1045 	}
1046 	if (isv6) {
1047 		const struct sockaddr_in6 *sin6;
1048 
1049 		/* LINTED: alignment */
1050 		sin6 = (const struct sockaddr_in6 *)cp;
1051 		if ((const char *)(sin6 + 1) > lim)
1052 			return (B_FALSE);
1053 		if (sin6->sin6_family != AF_INET6)
1054 			return (B_FALSE);
1055 		return (IN6_ARE_ADDR_EQUAL(&sin6->sin6_addr, addr));
1056 	} else {
1057 		const struct sockaddr_in *sinp;
1058 		ipaddr_t v4addr;
1059 
1060 		/* LINTED: alignment */
1061 		sinp = (const struct sockaddr_in *)cp;
1062 		if ((const char *)(sinp + 1) > lim)
1063 			return (B_FALSE);
1064 		if (sinp->sin_family != AF_INET)
1065 			return (B_FALSE);
1066 		IN6_V4MAPPED_TO_IPADDR(addr, v4addr);
1067 		return (sinp->sin_addr.s_addr == v4addr);
1068 	}
1069 }
1070 
1071 /*
1072  * is_rtm_v6(): determine if routing socket message is IPv6
1073  *
1074  *   input: struct ifa_msghdr *: pointer to routing socket message
1075  *	    int: message length
1076  *  output: boolean_t
1077  */
1078 
1079 static boolean_t
1080 is_rtm_v6(const struct ifa_msghdr *ifam, int msglen)
1081 {
1082 	const char *cp, *lim;
1083 	uint_t flag;
1084 	const struct sockaddr *sa;
1085 
1086 	cp = (const char *)(ifam + 1);
1087 	lim = (const char *)ifam + msglen;
1088 	for (flag = ifam->ifam_addrs; flag != 0; flag &= flag - 1) {
1089 		/* LINTED: alignment */
1090 		sa = (const struct sockaddr *)cp;
1091 		if ((const char *)(sa + 1) > lim)
1092 			return (B_FALSE);
1093 		switch (sa->sa_family) {
1094 		case AF_INET:
1095 			return (B_FALSE);
1096 		case AF_LINK:
1097 			cp += sizeof (struct sockaddr_dl);
1098 			break;
1099 		case AF_INET6:
1100 			return (B_TRUE);
1101 		default:
1102 			cp += sizeof (struct sockaddr);
1103 			break;
1104 		}
1105 	}
1106 	return (B_FALSE);
1107 }
1108 
1109 /*
1110  * check_lif(): check the state of a given logical interface and its DHCP
1111  *		lease.  We've been told by the routing socket that the
1112  *		corresponding ifIndex has changed.  This may mean that DAD has
1113  *		completed or failed.
1114  *
1115  *   input: dhcp_lif_t *: pointer to the LIF
1116  *	    const struct ifa_msghdr *: routing socket message
1117  *	    int: size of routing socket message
1118  *  output: boolean_t: B_TRUE if DAD has completed on this interface
1119  */
1120 
1121 static boolean_t
1122 check_lif(dhcp_lif_t *lif, const struct ifa_msghdr *ifam, int msglen)
1123 {
1124 	boolean_t isv6, dad_wait, unplumb;
1125 	int fd;
1126 	struct lifreq lifr;
1127 
1128 	isv6 = lif->lif_pif->pif_isv6;
1129 	fd = isv6 ? v6_sock_fd : v4_sock_fd;
1130 
1131 	/*
1132 	 * Get the real (64 bit) logical interface flags.  Note that the
1133 	 * routing socket message has flags, but these are just the lower 32
1134 	 * bits.
1135 	 */
1136 	unplumb = B_FALSE;
1137 	(void) memset(&lifr, 0, sizeof (lifr));
1138 	(void) strlcpy(lifr.lifr_name, lif->lif_name, sizeof (lifr.lifr_name));
1139 	if (ioctl(fd, SIOCGLIFFLAGS, &lifr) == -1) {
1140 		/*
1141 		 * Failing to retrieve flags means that the interface is gone.
1142 		 * It hasn't failed to verify with DAD, but we still have to
1143 		 * give up on it.
1144 		 */
1145 		lifr.lifr_flags = 0;
1146 		if (errno == ENXIO) {
1147 			lif->lif_plumbed = B_FALSE;
1148 			dhcpmsg(MSG_INFO, "%s has been removed; abandoning",
1149 			    lif->lif_name);
1150 		} else {
1151 			dhcpmsg(MSG_ERR,
1152 			    "unable to retrieve interface flags on %s",
1153 			    lif->lif_name);
1154 		}
1155 		unplumb = B_TRUE;
1156 	} else if (!check_rtm_addr(ifam, msglen, isv6, &lif->lif_v6addr)) {
1157 		/*
1158 		 * If the message is not about this logical interface,
1159 		 * then just ignore it.
1160 		 */
1161 		return (B_FALSE);
1162 	} else if (lifr.lifr_flags & IFF_DUPLICATE) {
1163 		dhcpmsg(MSG_ERROR, "interface %s has duplicate address",
1164 		    lif->lif_name);
1165 		lif_mark_decline(lif, "duplicate address");
1166 		close_ip_lif(lif);
1167 	}
1168 
1169 	dad_wait = lif->lif_dad_wait;
1170 	if (dad_wait) {
1171 		dhcpmsg(MSG_VERBOSE, "check_lif: %s has finished DAD",
1172 		    lif->lif_name);
1173 		lif->lif_dad_wait = B_FALSE;
1174 	}
1175 
1176 	if (unplumb)
1177 		unplumb_lif(lif);
1178 
1179 	return (dad_wait);
1180 }
1181 
1182 /*
1183  * check_main_lif(): check the state of a main logical interface for a state
1184  *		     machine.  This is used only for DHCPv6.
1185  *
1186  *   input: dhcp_smach_t *: pointer to the state machine
1187  *	    const struct ifa_msghdr *: routing socket message
1188  *	    int: size of routing socket message
1189  *  output: boolean_t: B_TRUE if LIF is ok.
1190  */
1191 
1192 static boolean_t
1193 check_main_lif(dhcp_smach_t *dsmp, const struct ifa_msghdr *ifam, int msglen)
1194 {
1195 	dhcp_lif_t *lif = dsmp->dsm_lif;
1196 	struct lifreq lifr;
1197 
1198 	/*
1199 	 * Get the real (64 bit) logical interface flags.  Note that the
1200 	 * routing socket message has flags, but these are just the lower 32
1201 	 * bits.
1202 	 */
1203 	(void) memset(&lifr, 0, sizeof (lifr));
1204 	(void) strlcpy(lifr.lifr_name, lif->lif_name, sizeof (lifr.lifr_name));
1205 	if (ioctl(v6_sock_fd, SIOCGLIFFLAGS, &lifr) == -1) {
1206 		/*
1207 		 * Failing to retrieve flags means that the interface is gone.
1208 		 * Our state machine is now trash.
1209 		 */
1210 		if (errno == ENXIO) {
1211 			dhcpmsg(MSG_INFO, "%s has been removed; abandoning",
1212 			    lif->lif_name);
1213 		} else {
1214 			dhcpmsg(MSG_ERR,
1215 			    "unable to retrieve interface flags on %s",
1216 			    lif->lif_name);
1217 		}
1218 		return (B_FALSE);
1219 	} else if (!check_rtm_addr(ifam, msglen, B_TRUE, &lif->lif_v6addr)) {
1220 		/*
1221 		 * If the message is not about this logical interface,
1222 		 * then just ignore it.
1223 		 */
1224 		return (B_TRUE);
1225 	} else if (lifr.lifr_flags & IFF_DUPLICATE) {
1226 		dhcpmsg(MSG_ERROR, "interface %s has duplicate address",
1227 		    lif->lif_name);
1228 		return (B_FALSE);
1229 	} else {
1230 		return (B_TRUE);
1231 	}
1232 }
1233 
1234 /*
1235  * process_link_up_down(): check the state of a physical interface for up/down
1236  *			   transitions; must go through INIT_REBOOT state if
1237  *			   the link flaps.
1238  *
1239  *   input: dhcp_pif_t *: pointer to the physical interface to check
1240  *	    const struct if_msghdr *: routing socket message
1241  *  output: none
1242  */
1243 
1244 static void
1245 process_link_up_down(dhcp_pif_t *pif, const struct if_msghdr *ifm)
1246 {
1247 	struct lifreq lifr;
1248 	boolean_t isv6;
1249 	int fd;
1250 
1251 	/*
1252 	 * If the message implies no change of flags, then we're done; no need
1253 	 * to check further.  Note that if we have multiple state machines on a
1254 	 * single physical interface, this test keeps us from issuing an ioctl
1255 	 * for each one.
1256 	 */
1257 	if ((ifm->ifm_flags & IFF_RUNNING) && pif->pif_running ||
1258 	    !(ifm->ifm_flags & IFF_RUNNING) && !pif->pif_running)
1259 		return;
1260 
1261 	/*
1262 	 * We don't know what the real interface flags are, because the
1263 	 * if_index number is only 16 bits; we must go ask.
1264 	 */
1265 	isv6 = pif->pif_isv6;
1266 	fd = isv6 ? v6_sock_fd : v4_sock_fd;
1267 	(void) memset(&lifr, 0, sizeof (lifr));
1268 	(void) strlcpy(lifr.lifr_name, pif->pif_name, sizeof (lifr.lifr_name));
1269 
1270 	if (ioctl(fd, SIOCGLIFFLAGS, &lifr) == -1 ||
1271 	    !(lifr.lifr_flags & IFF_RUNNING)) {
1272 		/*
1273 		 * If we've lost the interface or it has gone down, then
1274 		 * nothing special to do; just turn off the running flag.
1275 		 */
1276 		pif_status(pif, B_FALSE);
1277 	} else {
1278 		/*
1279 		 * Interface has come back up: go through verification process.
1280 		 */
1281 		pif_status(pif, B_TRUE);
1282 	}
1283 }
1284 
1285 /*
1286  * rtsock_event(): fetches routing socket messages and updates internal
1287  *		   interface state based on those messages.
1288  *
1289  *   input: iu_eh_t *: unused
1290  *	    int: the routing socket file descriptor
1291  *	    (other arguments unused)
1292  *  output: void
1293  */
1294 
1295 /* ARGSUSED */
1296 static void
1297 rtsock_event(iu_eh_t *ehp, int fd, short events, iu_event_id_t id, void *arg)
1298 {
1299 	dhcp_smach_t *dsmp, *dsmnext;
1300 	union {
1301 		struct ifa_msghdr ifam;
1302 		struct if_msghdr ifm;
1303 		char buf[1024];
1304 	} msg;
1305 	uint16_t ifindex;
1306 	int msglen;
1307 	boolean_t isv6;
1308 
1309 	if ((msglen = read(fd, &msg, sizeof (msg))) <= 0)
1310 		return;
1311 
1312 	/* Note that the routing socket interface index is just 16 bits */
1313 	if (msg.ifm.ifm_type == RTM_IFINFO) {
1314 		ifindex = msg.ifm.ifm_index;
1315 		isv6 = (msg.ifm.ifm_flags & IFF_IPV6) ? B_TRUE : B_FALSE;
1316 	} else if (msg.ifam.ifam_type == RTM_DELADDR ||
1317 	    msg.ifam.ifam_type == RTM_NEWADDR) {
1318 		ifindex = msg.ifam.ifam_index;
1319 		isv6 = is_rtm_v6(&msg.ifam, msglen);
1320 	} else {
1321 		return;
1322 	}
1323 
1324 	for (dsmp = lookup_smach_by_uindex(ifindex, NULL, isv6);
1325 	    dsmp != NULL; dsmp = dsmnext) {
1326 		DHCPSTATE oldstate;
1327 		boolean_t lif_finished;
1328 		boolean_t lease_removed;
1329 		dhcp_lease_t *dlp, *dlnext;
1330 
1331 		/*
1332 		 * Note that script_start can call dhcp_drop directly, and
1333 		 * that will do release_smach.
1334 		 */
1335 		dsmnext = lookup_smach_by_uindex(ifindex, dsmp, isv6);
1336 		oldstate = dsmp->dsm_state;
1337 
1338 		/*
1339 		 * Look for link up/down notifications.  These occur on a
1340 		 * physical interface basis.
1341 		 */
1342 		if (msg.ifm.ifm_type == RTM_IFINFO) {
1343 			process_link_up_down(dsmp->dsm_lif->lif_pif, &msg.ifm);
1344 			continue;
1345 		}
1346 
1347 		/*
1348 		 * Since we cannot trust the flags reported by the routing
1349 		 * socket (they're just 32 bits -- and thus never include
1350 		 * IFF_DUPLICATE), and we can't trust the ifindex (it's only 16
1351 		 * bits and also doesn't reflect the alias in use), we get
1352 		 * flags on all matching interfaces, and go by that.
1353 		 */
1354 		lif_finished = B_FALSE;
1355 		lease_removed = B_FALSE;
1356 		for (dlp = dsmp->dsm_leases; dlp != NULL; dlp = dlnext) {
1357 			dhcp_lif_t *lif, *lifnext;
1358 			uint_t nlifs = dlp->dl_nlifs;
1359 
1360 			dlnext = dlp->dl_next;
1361 			for (lif = dlp->dl_lifs; lif != NULL && nlifs > 0;
1362 			    lif = lifnext, nlifs--) {
1363 				lifnext = lif->lif_next;
1364 				if (check_lif(lif, &msg.ifam, msglen)) {
1365 					dsmp->dsm_lif_wait--;
1366 					lif_finished = B_TRUE;
1367 				}
1368 			}
1369 			if (dlp->dl_nlifs == 0) {
1370 				remove_lease(dlp);
1371 				lease_removed = B_TRUE;
1372 			}
1373 		}
1374 
1375 		if ((isv6 && !check_main_lif(dsmp, &msg.ifam, msglen)) ||
1376 		    (!isv6 && !verify_lif(dsmp->dsm_lif))) {
1377 			if (dsmp->dsm_script_pid != -1)
1378 				script_stop(dsmp);
1379 			(void) script_start(dsmp, EVENT_DROP6, dhcp_drop, NULL,
1380 			    NULL);
1381 			continue;
1382 		}
1383 
1384 		/*
1385 		 * Ignore this state machine if nothing interesting has
1386 		 * happened.
1387 		 */
1388 		if (!lif_finished && dsmp->dsm_lif_down == 0 &&
1389 		    (dsmp->dsm_leases != NULL || !lease_removed))
1390 			continue;
1391 
1392 		/*
1393 		 * If we're still waiting for DAD to complete on some of the
1394 		 * configured LIFs, then don't send a response.
1395 		 */
1396 		if (dsmp->dsm_lif_wait != 0) {
1397 			dhcpmsg(MSG_VERBOSE, "rtsock_event: %s still has %d "
1398 			    "LIFs waiting on DAD", dsmp->dsm_name,
1399 			    dsmp->dsm_lif_wait);
1400 			continue;
1401 		}
1402 
1403 		/*
1404 		 * If we have some failed LIFs, then handle them now.  We'll
1405 		 * remove them from the list.  Any leases that become empty are
1406 		 * also removed as part of the decline-generation process.
1407 		 */
1408 		if (dsmp->dsm_lif_down != 0) {
1409 			/*
1410 			 * We need to switch back to PRE_BOUND state so that
1411 			 * send_pkt_internal() uses DLPI instead of sockets.
1412 			 * Our logical interface has already been torn down by
1413 			 * the kernel, and thus we can't send DHCPDECLINE by
1414 			 * way of regular IP.  (Unless we're adopting -- allow
1415 			 * the grandparent to be handled as expected.)
1416 			 */
1417 			if (oldstate != ADOPTING) {
1418 				(void) set_smach_state(dsmp, PRE_BOUND);
1419 			}
1420 			send_declines(dsmp);
1421 		}
1422 
1423 		if (dsmp->dsm_leases == NULL) {
1424 			dsmp->dsm_bad_offers++;
1425 			/*
1426 			 * For DHCPv6, we'll process the restart once we're
1427 			 * done sending Decline messages, because these are
1428 			 * supposed to be acknowledged.  With DHCPv4, there's
1429 			 * no acknowledgment for a DECLINE, so after sending
1430 			 * it, we just restart right away.
1431 			 */
1432 			if (!dsmp->dsm_isv6) {
1433 				dhcpmsg(MSG_VERBOSE, "rtsock_event: %s has no "
1434 				    "LIFs left; restarting", dsmp->dsm_name);
1435 				dhcp_restart(dsmp);
1436 			}
1437 		} else {
1438 			/*
1439 			 * If we're now up on at least some of the leases and
1440 			 * we were waiting for that, then kick off the rest of
1441 			 * configuration.  Lease validation and DAD are done.
1442 			 */
1443 			dhcpmsg(MSG_VERBOSE, "rtsock_event: all LIFs verified "
1444 			    "on %s in %s state", dsmp->dsm_name,
1445 			    dhcp_state_to_string(oldstate));
1446 			if (oldstate == PRE_BOUND ||
1447 			    oldstate == ADOPTING)
1448 				dhcp_bound_complete(dsmp);
1449 			if (oldstate == ADOPTING)
1450 				dhcp_adopt_complete(dsmp);
1451 		}
1452 	}
1453 }
1454 
1455 /*
1456  * check_cmd_allowed(): check whether the requested command is allowed in the
1457  *			state specified.
1458  *
1459  *   input: DHCPSTATE: current state
1460  *	    dhcp_ipc_type_t: requested command
1461  *  output: boolean_t: B_TRUE if command is allowed in this state
1462  */
1463 
1464 boolean_t
1465 check_cmd_allowed(DHCPSTATE state, dhcp_ipc_type_t cmd)
1466 {
1467 	return (ipc_cmd_allowed[state][cmd] != 0);
1468 }
1469