xref: /titanic_44/usr/src/cmd/cmd-inet/usr.lib/inetd/inetd.c (revision de33058aebd1018422519c8262583a3e5871d75c)
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 2010 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*
27  * NOTES: To be expanded.
28  *
29  * The SMF inetd.
30  *
31  * Below are some high level notes of the operation of the SMF inetd. The
32  * notes don't go into any real detail, and the viewer of this file is
33  * encouraged to look at the code and its associated comments to better
34  * understand inetd's operation. This saves the potential for the code
35  * and these notes diverging over time.
36  *
37  * Inetd's major work is done from the context of event_loop(). Within this
38  * loop, inetd polls for events arriving from a number of different file
39  * descriptors, representing the following event types, and initiates
40  * any necessary event processing:
41  * - incoming network connections/datagrams.
42  * - notification of terminated processes (discovered via contract events).
43  * - instance specific events originating from the SMF master restarter.
44  * - stop/refresh requests from the inetd method processes (coming in on a
45  *   Unix Domain socket).
46  * There's also a timeout set for the poll, which is set to the nearest
47  * scheduled timer in a timer queue that inetd uses to perform delayed
48  * processing, such as bind retries.
49  * The SIGHUP and SIGINT signals can also interrupt the poll, and will
50  * result in inetd being refreshed or stopped respectively, as was the
51  * behavior with the old inetd.
52  *
53  * Inetd implements a state machine for each instance. The states within the
54  * machine are: offline, online, disabled, maintenance, uninitialized and
55  * specializations of the offline state for when an instance exceeds one of
56  * its DOS limits. The state of an instance can be changed as a
57  * result/side-effect of one of the above events occurring, or inetd being
58  * started up. The ongoing state of an instance is stored in the SMF
59  * repository, as required of SMF restarters. This enables an administrator
60  * to view the state of each instance, and, if inetd was to terminate
61  * unexpectedly, it could use the stored state to re-commence where it left off.
62  *
63  * Within the state machine a number of methods are run (if provided) as part
64  * of a state transition to aid/ effect a change in an instance's state. The
65  * supported methods are: offline, online, disable, refresh and start. The
66  * latter of these is the equivalent of the server program and its arguments
67  * in the old inetd.
68  *
69  * Events from the SMF master restarter come in on a number of threads
70  * created in the registration routine of librestart, the delegated restarter
71  * library. These threads call into the restart_event_proxy() function
72  * when an event arrives. To serialize the processing of instances, these events
73  * are then written down a pipe to the process's main thread, which listens
74  * for these events via a poll call, with the file descriptor of the other
75  * end of the pipe in its read set, and processes the event appropriately.
76  * When the event has been  processed (which may be delayed if the instance
77  * for which the event is for is in the process of executing one of its methods
78  * as part of a state transition) it writes an acknowledgement back down the
79  * pipe the event was received on. The thread in restart_event_proxy() that
80  * wrote the event will read the acknowledgement it was blocked upon, and will
81  * then be able to return to its caller, thus implicitly acknowledging the
82  * event, and allowing another event to be written down the pipe for the main
83  * thread to process.
84  */
85 
86 
87 #include <netdb.h>
88 #include <stdio.h>
89 #include <stdio_ext.h>
90 #include <stdlib.h>
91 #include <strings.h>
92 #include <unistd.h>
93 #include <assert.h>
94 #include <sys/types.h>
95 #include <sys/socket.h>
96 #include <netinet/in.h>
97 #include <fcntl.h>
98 #include <signal.h>
99 #include <errno.h>
100 #include <locale.h>
101 #include <syslog.h>
102 #include <libintl.h>
103 #include <librestart.h>
104 #include <pthread.h>
105 #include <sys/stat.h>
106 #include <time.h>
107 #include <limits.h>
108 #include <libgen.h>
109 #include <tcpd.h>
110 #include <libscf.h>
111 #include <libuutil.h>
112 #include <stddef.h>
113 #include <bsm/adt_event.h>
114 #include <ucred.h>
115 #include "inetd_impl.h"
116 
117 /* path to inetd's binary */
118 #define	INETD_PATH	"/usr/lib/inet/inetd"
119 
120 /*
121  * inetd's default configuration file paths. /etc/inetd/inetd.conf is set
122  * be be the primary file, so it is checked before /etc/inetd.conf.
123  */
124 #define	PRIMARY_DEFAULT_CONF_FILE	"/etc/inet/inetd.conf"
125 #define	SECONDARY_DEFAULT_CONF_FILE	"/etc/inetd.conf"
126 
127 /* Arguments passed to this binary to request which method to execute. */
128 #define	START_METHOD_ARG	"start"
129 #define	STOP_METHOD_ARG		"stop"
130 #define	REFRESH_METHOD_ARG	"refresh"
131 
132 /* connection backlog for unix domain socket */
133 #define	UDS_BACKLOG	2
134 
135 /* number of retries to recv() a request on the UDS socket before giving up */
136 #define	UDS_RECV_RETRIES	10
137 
138 /* enumeration of the different ends of a pipe */
139 enum pipe_end {
140 	PE_CONSUMER,
141 	PE_PRODUCER
142 };
143 
144 typedef struct {
145 	internal_inst_state_t		istate;
146 	const char			*name;
147 	restarter_instance_state_t	smf_state;
148 	instance_method_t		method_running;
149 } state_info_t;
150 
151 
152 /*
153  * Collection of information for each state.
154  * NOTE:  This table is indexed into using the internal_inst_state_t
155  * enumeration, so the ordering needs to be kept in synch.
156  */
157 static state_info_t states[] = {
158 	{IIS_UNINITIALIZED, "uninitialized", RESTARTER_STATE_UNINIT,
159 	    IM_NONE},
160 	{IIS_ONLINE, "online", RESTARTER_STATE_ONLINE, IM_START},
161 	{IIS_IN_ONLINE_METHOD, "online_method", RESTARTER_STATE_OFFLINE,
162 	    IM_ONLINE},
163 	{IIS_OFFLINE, "offline", RESTARTER_STATE_OFFLINE, IM_NONE},
164 	{IIS_IN_OFFLINE_METHOD, "offline_method", RESTARTER_STATE_OFFLINE,
165 	    IM_OFFLINE},
166 	{IIS_DISABLED, "disabled", RESTARTER_STATE_DISABLED, IM_NONE},
167 	{IIS_IN_DISABLE_METHOD, "disabled_method", RESTARTER_STATE_OFFLINE,
168 	    IM_DISABLE},
169 	{IIS_IN_REFRESH_METHOD, "refresh_method", RESTARTER_STATE_ONLINE,
170 	    IM_REFRESH},
171 	{IIS_MAINTENANCE, "maintenance", RESTARTER_STATE_MAINT, IM_NONE},
172 	{IIS_OFFLINE_CONRATE, "cr_offline", RESTARTER_STATE_OFFLINE, IM_NONE},
173 	{IIS_OFFLINE_BIND, "bind_offline", RESTARTER_STATE_OFFLINE, IM_NONE},
174 	{IIS_OFFLINE_COPIES, "copies_offline", RESTARTER_STATE_OFFLINE,
175 	    IM_NONE},
176 	{IIS_DEGRADED, "degraded", RESTARTER_STATE_DEGRADED, IM_NONE},
177 	{IIS_NONE, "none", RESTARTER_STATE_NONE, IM_NONE}
178 };
179 
180 /*
181  * Pipe used to send events from the threads created by restarter_bind_handle()
182  * to the main thread of control.
183  */
184 static int			rst_event_pipe[] = {-1, -1};
185 /*
186  * Used to protect the critical section of code in restarter_event_proxy() that
187  * involves writing an event down the event pipe and reading an acknowledgement.
188  */
189 static pthread_mutex_t		rst_event_pipe_mtx = PTHREAD_MUTEX_INITIALIZER;
190 
191 /* handle used in communication with the master restarter */
192 static restarter_event_handle_t *rst_event_handle = NULL;
193 
194 /* set to indicate a refresh of inetd is requested */
195 static boolean_t		refresh_inetd_requested = B_FALSE;
196 
197 /* set by the SIGTERM handler to flag we got a SIGTERM */
198 static boolean_t		got_sigterm = B_FALSE;
199 
200 /*
201  * Timer queue used to store timers for delayed event processing, such as
202  * bind retries.
203  */
204 iu_tq_t				*timer_queue = NULL;
205 
206 /*
207  * fd of Unix Domain socket used to communicate stop and refresh requests
208  * to the inetd start method process.
209  */
210 static int			uds_fd = -1;
211 
212 /*
213  * List of inetd's currently managed instances; each containing its state,
214  * and in certain states its configuration.
215  */
216 static uu_list_pool_t		*instance_pool = NULL;
217 uu_list_t			*instance_list = NULL;
218 
219 /* set to indicate we're being stopped */
220 boolean_t			inetd_stopping = B_FALSE;
221 
222 /* TCP wrappers syslog globals. Consumed by libwrap. */
223 int				allow_severity = LOG_INFO;
224 int				deny_severity = LOG_WARNING;
225 
226 /* path of the configuration file being monitored by check_conf_file() */
227 static char			*conf_file = NULL;
228 
229 /* Auditing session handle */
230 static adt_session_data_t	*audit_handle;
231 
232 /* Number of pending connections */
233 static size_t			tlx_pending_counter;
234 
235 static void uds_fini(void);
236 static int uds_init(void);
237 static int run_method(instance_t *, instance_method_t, const proto_info_t *);
238 static void create_bound_fds(instance_t *);
239 static void destroy_bound_fds(instance_t *);
240 static void destroy_instance(instance_t *);
241 static void inetd_stop(void);
242 static void
243 exec_method(instance_t *instance, instance_method_t method, method_info_t *mi,
244     struct method_context *mthd_ctxt, const proto_info_t *pi) __NORETURN;
245 
246 /*
247  * The following two functions are callbacks that libumem uses to determine
248  * inetd's desired debugging/logging levels. The interface they consume is
249  * exported by FMA and is consolidation private. The comments in the two
250  * functions give the environment variable that will effectively be set to
251  * their returned value, and thus whose behavior for this value, described in
252  * umem_debug(3MALLOC), will be followed.
253  */
254 
255 const char *
256 _umem_debug_init(void)
257 {
258 	return ("default,verbose");	/* UMEM_DEBUG setting */
259 }
260 
261 const char *
262 _umem_logging_init(void)
263 {
264 	return ("fail,contents");	/* UMEM_LOGGING setting */
265 }
266 
267 static void
268 log_invalid_cfg(const char *fmri)
269 {
270 	error_msg(gettext(
271 	    "Invalid configuration for instance %s, placing in maintenance"),
272 	    fmri);
273 }
274 
275 /*
276  * Returns B_TRUE if the instance is in a suitable state for inetd to stop.
277  */
278 static boolean_t
279 instance_stopped(const instance_t *inst)
280 {
281 	return ((inst->cur_istate == IIS_OFFLINE) ||
282 	    (inst->cur_istate == IIS_MAINTENANCE) ||
283 	    (inst->cur_istate == IIS_DISABLED) ||
284 	    (inst->cur_istate == IIS_UNINITIALIZED));
285 }
286 
287 /*
288  * Given the instance fmri, obtain the corresonding scf_instance.
289  * Caller is responsible for freeing the returned scf_instance and
290  * its scf_handle.
291  */
292 static int
293 fmri_to_instance(char *fmri, scf_instance_t **scf_instp)
294 {
295 	int retries, ret = 1;
296 	scf_handle_t	*h;
297 	scf_instance_t *scf_inst;
298 
299 	if ((h = scf_handle_create(SCF_VERSION)) == NULL) {
300 		error_msg(gettext("Failed to get instance for %s"), fmri);
301 		return (1);
302 	}
303 
304 	if ((scf_inst = scf_instance_create(h)) == NULL)
305 		goto out;
306 
307 	for (retries = 0; retries <= REP_OP_RETRIES; retries++) {
308 		if (make_handle_bound(h) == -1)
309 			break;
310 
311 		if (scf_handle_decode_fmri(h, fmri, NULL, NULL, scf_inst,
312 		    NULL, NULL, SCF_DECODE_FMRI_EXACT) == 0) {
313 			ret = 0;
314 			*scf_instp = scf_inst;
315 			break;
316 		}
317 
318 		if (scf_error() != SCF_ERROR_CONNECTION_BROKEN)
319 			break;
320 	}
321 
322 out:
323 	if (ret != 0) {
324 		error_msg(gettext("Failed to get instance for %s"), fmri);
325 		scf_instance_destroy(scf_inst);
326 		scf_handle_destroy(h);
327 	}
328 
329 	return (ret);
330 }
331 
332 /*
333  * Updates the current and next repository states of instance 'inst'. If
334  * any errors occur an error message is output.
335  */
336 static void
337 update_instance_states(instance_t *inst, internal_inst_state_t new_cur_state,
338     internal_inst_state_t new_next_state, restarter_error_t err)
339 {
340 	internal_inst_state_t	old_cur = inst->cur_istate;
341 	internal_inst_state_t	old_next = inst->next_istate;
342 	scf_instance_t		*scf_inst = NULL;
343 	scf_error_t		sret;
344 	int			ret;
345 	char			*aux = "none";
346 
347 	/* update the repository/cached internal state */
348 	inst->cur_istate = new_cur_state;
349 	inst->next_istate = new_next_state;
350 	(void) set_single_rep_val(inst->cur_istate_rep,
351 	    (int64_t)new_cur_state);
352 	(void) set_single_rep_val(inst->next_istate_rep,
353 	    (int64_t)new_next_state);
354 
355 	if (((sret = store_rep_vals(inst->cur_istate_rep, inst->fmri,
356 	    PR_NAME_CUR_INT_STATE)) != 0) ||
357 	    ((sret = store_rep_vals(inst->next_istate_rep, inst->fmri,
358 	    PR_NAME_NEXT_INT_STATE)) != 0))
359 		error_msg(gettext("Failed to update state of instance %s in "
360 		    "repository: %s"), inst->fmri, scf_strerror(sret));
361 
362 	if (fmri_to_instance(inst->fmri, &scf_inst) == 0) {
363 		/*
364 		 * If transitioning to maintenance, check auxiliary_tty set
365 		 * by svcadm and assign appropriate value to auxiliary_state.
366 		 * If the maintenance event comes from a service request,
367 		 * validate auxiliary_fmri and copy it to
368 		 * restarter/auxiliary_fmri.
369 		 */
370 		if (new_cur_state == IIS_MAINTENANCE) {
371 			if (restarter_inst_ractions_from_tty(scf_inst) == 0)
372 				aux = "service_request";
373 			else
374 				aux = "administrative_request";
375 		}
376 
377 		if (strcmp(aux, "service_request") == 0) {
378 			if (restarter_inst_validate_ractions_aux_fmri(
379 			    scf_inst) == 0) {
380 				if (restarter_inst_set_aux_fmri(scf_inst))
381 					error_msg(gettext("Could not set "
382 					    "auxiliary_fmri property for %s"),
383 					    inst->fmri);
384 			} else {
385 				if (restarter_inst_reset_aux_fmri(scf_inst))
386 					error_msg(gettext("Could not reset "
387 					    "auxiliary_fmri property for %s"),
388 					    inst->fmri);
389 			}
390 		}
391 		scf_handle_destroy(scf_instance_handle(scf_inst));
392 		scf_instance_destroy(scf_inst);
393 	}
394 
395 	/* update the repository SMF state */
396 	if ((ret = restarter_set_states(rst_event_handle, inst->fmri,
397 	    states[old_cur].smf_state, states[new_cur_state].smf_state,
398 	    states[old_next].smf_state, states[new_next_state].smf_state,
399 	    err, aux)) != 0)
400 		error_msg(gettext("Failed to update state of instance %s in "
401 		    "repository: %s"), inst->fmri, strerror(ret));
402 }
403 
404 void
405 update_state(instance_t *inst, internal_inst_state_t new_cur,
406     restarter_error_t err)
407 {
408 	update_instance_states(inst, new_cur, IIS_NONE, err);
409 }
410 
411 /*
412  * Sends a refresh event to the inetd start method process and returns
413  * SMF_EXIT_OK if it managed to send it. If it fails to send the request for
414  * some reason it returns SMF_EXIT_ERR_OTHER.
415  */
416 static int
417 refresh_method(void)
418 {
419 	uds_request_t   req = UR_REFRESH_INETD;
420 	int		fd;
421 
422 	if ((fd = connect_to_inetd()) < 0) {
423 		error_msg(gettext("Failed to connect to inetd: %s"),
424 		    strerror(errno));
425 		return (SMF_EXIT_ERR_OTHER);
426 	}
427 
428 	/* write the request and return success */
429 	if (safe_write(fd, &req, sizeof (req)) == -1) {
430 		error_msg(
431 		    gettext("Failed to send refresh request to inetd: %s"),
432 		    strerror(errno));
433 		(void) close(fd);
434 		return (SMF_EXIT_ERR_OTHER);
435 	}
436 
437 	(void) close(fd);
438 
439 	return (SMF_EXIT_OK);
440 }
441 
442 /*
443  * Sends a stop event to the inetd start method process and wait till it goes
444  * away. If inetd is determined to have stopped SMF_EXIT_OK is returned, else
445  * SMF_EXIT_ERR_OTHER is returned.
446  */
447 static int
448 stop_method(void)
449 {
450 	uds_request_t   req = UR_STOP_INETD;
451 	int		fd;
452 	char		c;
453 	ssize_t		ret;
454 
455 	if ((fd = connect_to_inetd()) == -1) {
456 		debug_msg(gettext("Failed to connect to inetd: %s"),
457 		    strerror(errno));
458 		/*
459 		 * Assume connect_to_inetd() failed because inetd was already
460 		 * stopped, and return success.
461 		 */
462 		return (SMF_EXIT_OK);
463 	}
464 
465 	/*
466 	 * This is safe to do since we're fired off in a separate process
467 	 * than inetd and in the case we get wedged, the stop method timeout
468 	 * will occur and we'd be killed by our restarter.
469 	 */
470 	enable_blocking(fd);
471 
472 	/* write the stop request to inetd and wait till it goes away */
473 	if (safe_write(fd, &req, sizeof (req)) != 0) {
474 		error_msg(gettext("Failed to send stop request to inetd"));
475 		(void) close(fd);
476 		return (SMF_EXIT_ERR_OTHER);
477 	}
478 
479 	/* wait until remote end of socket is closed */
480 	while (((ret = recv(fd, &c, sizeof (c), 0)) != 0) && (errno == EINTR))
481 		;
482 
483 	(void) close(fd);
484 
485 	if (ret != 0) {
486 		error_msg(gettext("Failed to determine whether inetd stopped"));
487 		return (SMF_EXIT_ERR_OTHER);
488 	}
489 
490 	return (SMF_EXIT_OK);
491 }
492 
493 
494 /*
495  * This function is called to handle restarter events coming in from the
496  * master restarter. It is registered with the master restarter via
497  * restarter_bind_handle() and simply passes a pointer to the event down
498  * the event pipe, which will be discovered by the poll in the event loop
499  * and processed there. It waits for an acknowledgement to be written back down
500  * the pipe before returning.
501  * Writing a pointer to the function's 'event' parameter down the pipe will
502  * be safe, as the thread in restarter_event_proxy() doesn't return until
503  * the main thread has finished its processing of the passed event, thus
504  * the referenced event will remain around until the function returns.
505  * To impose the limit of only one event being in the pipe and processed
506  * at once, a lock is taken on entry to this function and returned on exit.
507  * Always returns 0.
508  */
509 static int
510 restarter_event_proxy(restarter_event_t *event)
511 {
512 	boolean_t		processed;
513 
514 	(void) pthread_mutex_lock(&rst_event_pipe_mtx);
515 
516 	/* write the event to the main worker thread down the pipe */
517 	if (safe_write(rst_event_pipe[PE_PRODUCER], &event,
518 	    sizeof (event)) != 0)
519 		goto pipe_error;
520 
521 	/*
522 	 * Wait for an acknowledgement that the event has been processed from
523 	 * the same pipe. In the case that inetd is stopping, any thread in
524 	 * this function will simply block on this read until inetd eventually
525 	 * exits. This will result in this function not returning success to
526 	 * its caller, and the event that was being processed when the
527 	 * function exited will be re-sent when inetd is next started.
528 	 */
529 	if (safe_read(rst_event_pipe[PE_PRODUCER], &processed,
530 	    sizeof (processed)) != 0)
531 		goto pipe_error;
532 
533 	(void) pthread_mutex_unlock(&rst_event_pipe_mtx);
534 
535 	return (processed ? 0 : EAGAIN);
536 
537 pipe_error:
538 	/*
539 	 * Something's seriously wrong with the event pipe. Notify the
540 	 * worker thread by closing this end of the event pipe and pause till
541 	 * inetd exits.
542 	 */
543 	error_msg(gettext("Can't process restarter events: %s"),
544 	    strerror(errno));
545 	(void) close(rst_event_pipe[PE_PRODUCER]);
546 	for (;;)
547 		(void) pause();
548 
549 	/* NOTREACHED */
550 }
551 
552 /*
553  * Let restarter_event_proxy() know we're finished with the event it's blocked
554  * upon. The 'processed' argument denotes whether we successfully processed the
555  * event.
556  */
557 static void
558 ack_restarter_event(boolean_t processed)
559 {
560 	/*
561 	 * If safe_write returns -1 something's seriously wrong with the event
562 	 * pipe, so start the shutdown proceedings.
563 	 */
564 	if (safe_write(rst_event_pipe[PE_CONSUMER], &processed,
565 	    sizeof (processed)) == -1)
566 		inetd_stop();
567 }
568 
569 /*
570  * Switch the syslog identification string to 'ident'.
571  */
572 static void
573 change_syslog_ident(const char *ident)
574 {
575 	closelog();
576 	openlog(ident, LOG_PID|LOG_CONS, LOG_DAEMON);
577 }
578 
579 /*
580  * Perform TCP wrappers checks on this instance. Due to the fact that the
581  * current wrappers code used in Solaris is taken untouched from the open
582  * source version, we're stuck with using the daemon name for the checks, as
583  * opposed to making use of instance FMRIs. Sigh.
584  * Returns B_TRUE if the check passed, else B_FALSE.
585  */
586 static boolean_t
587 tcp_wrappers_ok(instance_t *instance)
588 {
589 	boolean_t		rval = B_TRUE;
590 	char			*daemon_name;
591 	basic_cfg_t		*cfg = instance->config->basic;
592 	struct request_info	req;
593 
594 	/*
595 	 * Wrap the service using libwrap functions. The code below implements
596 	 * the functionality of tcpd. This is done only for stream,nowait
597 	 * services, following the convention of other vendors.  udp/dgram and
598 	 * stream/wait can NOT be wrapped with this libwrap, so be wary of
599 	 * changing the test below.
600 	 */
601 	if (cfg->do_tcp_wrappers && !cfg->iswait && !cfg->istlx) {
602 
603 		daemon_name = instance->config->methods[
604 		    IM_START]->exec_args_we.we_wordv[0];
605 		if (*daemon_name == '/')
606 			daemon_name = strrchr(daemon_name, '/') + 1;
607 
608 		/*
609 		 * Change the syslog message identity to the name of the
610 		 * daemon being wrapped, as opposed to "inetd".
611 		 */
612 		change_syslog_ident(daemon_name);
613 
614 		(void) request_init(&req, RQ_DAEMON, daemon_name, RQ_FILE,
615 		    instance->conn_fd, NULL);
616 		fromhost(&req);
617 
618 		if (strcasecmp(eval_hostname(req.client), paranoid) == 0) {
619 			syslog(deny_severity,
620 			    "refused connect from %s (name/address mismatch)",
621 			    eval_client(&req));
622 			if (req.sink != NULL)
623 				req.sink(instance->conn_fd);
624 			rval = B_FALSE;
625 		} else if (!hosts_access(&req)) {
626 			syslog(deny_severity,
627 			    "refused connect from %s (access denied)",
628 			    eval_client(&req));
629 			if (req.sink != NULL)
630 				req.sink(instance->conn_fd);
631 			rval = B_FALSE;
632 		} else {
633 			syslog(allow_severity, "connect from %s",
634 			    eval_client(&req));
635 		}
636 
637 		/* Revert syslog identity back to "inetd". */
638 		change_syslog_ident(SYSLOG_IDENT);
639 	}
640 	return (rval);
641 }
642 
643 /*
644  * Handler registered with the timer queue code to remove an instance from
645  * the connection rate offline state when it has been there for its allotted
646  * time.
647  */
648 /* ARGSUSED */
649 static void
650 conn_rate_online(iu_tq_t *tq, void *arg)
651 {
652 	instance_t *instance = arg;
653 
654 	assert(instance->cur_istate == IIS_OFFLINE_CONRATE);
655 	instance->timer_id = -1;
656 	update_state(instance, IIS_OFFLINE, RERR_RESTART);
657 	process_offline_inst(instance);
658 }
659 
660 /*
661  * Check whether this instance in the offline state is in transition to
662  * another state and do the work to continue this transition.
663  */
664 void
665 process_offline_inst(instance_t *inst)
666 {
667 	if (inst->disable_req) {
668 		inst->disable_req = B_FALSE;
669 		(void) run_method(inst, IM_DISABLE, NULL);
670 	} else if (inst->maintenance_req) {
671 		inst->maintenance_req = B_FALSE;
672 		update_state(inst, IIS_MAINTENANCE, RERR_RESTART);
673 	/*
674 	 * If inetd is in the process of stopping, we don't want to enter
675 	 * any states but offline, disabled and maintenance.
676 	 */
677 	} else if (!inetd_stopping) {
678 		if (inst->conn_rate_exceeded) {
679 			basic_cfg_t *cfg = inst->config->basic;
680 
681 			inst->conn_rate_exceeded = B_FALSE;
682 			update_state(inst, IIS_OFFLINE_CONRATE, RERR_RESTART);
683 			/*
684 			 * Schedule a timer to bring the instance out of the
685 			 * connection rate offline state.
686 			 */
687 			inst->timer_id = iu_schedule_timer(timer_queue,
688 			    cfg->conn_rate_offline, conn_rate_online,
689 			    inst);
690 			if (inst->timer_id == -1) {
691 				error_msg(gettext("%s unable to set timer, "
692 				    "won't be brought on line after %d "
693 				    "seconds."), inst->fmri,
694 				    cfg->conn_rate_offline);
695 			}
696 
697 		} else if (copies_limit_exceeded(inst)) {
698 			update_state(inst, IIS_OFFLINE_COPIES, RERR_RESTART);
699 		}
700 	}
701 }
702 
703 /*
704  * Create a socket bound to the instance's configured address. If the
705  * bind fails, returns -1, else the fd of the bound socket.
706  */
707 static int
708 create_bound_socket(const instance_t *inst, socket_info_t *sock_info)
709 {
710 	int		fd;
711 	int		on = 1;
712 	const char	*fmri = inst->fmri;
713 	rpc_info_t	*rpc = sock_info->pr_info.ri;
714 	const char	*proto = sock_info->pr_info.proto;
715 
716 	fd = socket(sock_info->local_addr.ss_family, sock_info->type,
717 	    sock_info->protocol);
718 	if (fd < 0) {
719 		error_msg(gettext(
720 		    "Socket creation failure for instance %s, proto %s: %s"),
721 		    fmri, proto, strerror(errno));
722 		return (-1);
723 	}
724 
725 	if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) == -1) {
726 		error_msg(gettext("setsockopt SO_REUSEADDR failed for service "
727 		    "instance %s, proto %s: %s"), fmri, proto, strerror(errno));
728 		(void) close(fd);
729 		return (-1);
730 	}
731 	if (inst->config->basic->do_tcp_keepalive &&
732 	    !inst->config->basic->iswait && !inst->config->basic->istlx) {
733 		/* set the keepalive option */
734 		if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &on,
735 		    sizeof (on)) == -1) {
736 			error_msg(gettext("setsockopt SO_KEEPALIVE failed for "
737 			    "service instance %s, proto %s: %s"), fmri,
738 			    proto, strerror(errno));
739 			(void) close(fd);
740 			return (-1);
741 		}
742 	}
743 	if (sock_info->pr_info.v6only) {
744 		/* restrict socket to IPv6 communications only */
745 		if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on,
746 		    sizeof (on)) == -1) {
747 			error_msg(gettext("setsockopt IPV6_V6ONLY failed for "
748 			    "service instance %s, proto %s: %s"), fmri, proto,
749 			    strerror(errno));
750 			(void) close(fd);
751 			return (-1);
752 		}
753 	}
754 
755 	if (rpc != NULL)
756 		SS_SETPORT(sock_info->local_addr, 0);
757 
758 	if (bind(fd, (struct sockaddr *)&(sock_info->local_addr),
759 	    SS_ADDRLEN(sock_info->local_addr)) < 0) {
760 		error_msg(gettext(
761 		    "Failed to bind to the port of service instance %s, "
762 		    "proto %s: %s"), fmri, proto, strerror(errno));
763 		(void) close(fd);
764 		return (-1);
765 	}
766 
767 	/*
768 	 * Retrieve and store the address bound to for RPC services.
769 	 */
770 	if (rpc != NULL) {
771 		struct sockaddr_storage	ss;
772 		int			ss_size = sizeof (ss);
773 
774 		if (getsockname(fd, (struct sockaddr *)&ss, &ss_size) < 0) {
775 			error_msg(gettext("Failed getsockname for instance %s, "
776 			    "proto %s: %s"), fmri, proto, strerror(errno));
777 			(void) close(fd);
778 			return (-1);
779 		}
780 		(void) memcpy(rpc->netbuf.buf, &ss,
781 		    sizeof (struct sockaddr_storage));
782 		rpc->netbuf.len = SS_ADDRLEN(ss);
783 		rpc->netbuf.maxlen = SS_ADDRLEN(ss);
784 	}
785 
786 	if (sock_info->type == SOCK_STREAM) {
787 		int qlen = inst->config->basic->conn_backlog;
788 
789 		debug_msg("Listening for service %s with backlog queue"
790 		    " size %d", fmri, qlen);
791 		(void) listen(fd, qlen);
792 	}
793 
794 	return (fd);
795 }
796 
797 /*
798  * Handler registered with the timer queue code to retry the creation
799  * of a bound fd.
800  */
801 /* ARGSUSED */
802 static void
803 retry_bind(iu_tq_t *tq, void *arg)
804 {
805 	instance_t *instance = arg;
806 
807 	switch (instance->cur_istate) {
808 	case IIS_OFFLINE_BIND:
809 	case IIS_ONLINE:
810 	case IIS_DEGRADED:
811 	case IIS_IN_ONLINE_METHOD:
812 	case IIS_IN_REFRESH_METHOD:
813 		break;
814 	default:
815 #ifndef NDEBUG
816 		(void) fprintf(stderr, "%s:%d: Unknown instance state %d.\n",
817 		    __FILE__, __LINE__, instance->cur_istate);
818 #endif
819 		abort();
820 	}
821 
822 	instance->bind_timer_id = -1;
823 	create_bound_fds(instance);
824 }
825 
826 /*
827  * For each of the fds for the given instance that are bound, if 'listen' is
828  * set add them to the poll set, else remove them from it. If proto_name is
829  * not NULL then apply the change only to this specific protocol endpoint.
830  * If any additions fail, returns -1, else 0 on success.
831  */
832 int
833 poll_bound_fds(instance_t *instance, boolean_t listen, char *proto_name)
834 {
835 	basic_cfg_t	*cfg = instance->config->basic;
836 	proto_info_t	*pi;
837 	int		ret = 0;
838 
839 	for (pi = uu_list_first(cfg->proto_list); pi != NULL;
840 	    pi = uu_list_next(cfg->proto_list, pi)) {
841 		if (pi->listen_fd != -1) {	/* fd bound */
842 			if (proto_name == NULL ||
843 			    strcmp(pi->proto, proto_name) == 0) {
844 				if (listen == B_FALSE) {
845 					clear_pollfd(pi->listen_fd);
846 				} else if (set_pollfd(pi->listen_fd,
847 				    POLLIN) == -1) {
848 					ret = -1;
849 				}
850 			}
851 		}
852 	}
853 
854 	return (ret);
855 }
856 
857 /*
858  * Handle the case were we either fail to create a bound fd or we fail
859  * to add a bound fd to the poll set for the given instance.
860  */
861 static void
862 handle_bind_failure(instance_t *instance)
863 {
864 	basic_cfg_t *cfg = instance->config->basic;
865 
866 	/*
867 	 * We must be being called as a result of a failed poll_bound_fds()
868 	 * as a bind retry is already scheduled. Just return and let it do
869 	 * the work.
870 	 */
871 	if (instance->bind_timer_id != -1)
872 		return;
873 
874 	/*
875 	 * Check if the rebind retries limit is operative and if so,
876 	 * if it has been reached.
877 	 */
878 	if (((cfg->bind_fail_interval <= 0) ||		/* no retries */
879 	    ((cfg->bind_fail_max >= 0) &&		/* limit reached */
880 	    (++instance->bind_fail_count > cfg->bind_fail_max))) ||
881 	    ((instance->bind_timer_id = iu_schedule_timer(timer_queue,
882 	    cfg->bind_fail_interval, retry_bind, instance)) == -1)) {
883 		proto_info_t *pi;
884 
885 		instance->bind_fail_count = 0;
886 
887 		switch (instance->cur_istate) {
888 		case IIS_DEGRADED:
889 		case IIS_ONLINE:
890 			/* check if any of the fds are being poll'd upon */
891 			for (pi = uu_list_first(cfg->proto_list); pi != NULL;
892 			    pi = uu_list_next(cfg->proto_list, pi)) {
893 				if ((pi->listen_fd != -1) &&
894 				    (find_pollfd(pi->listen_fd) != NULL))
895 					break;
896 			}
897 			if (pi != NULL)	{	/* polling on > 0 fds */
898 				warn_msg(gettext("Failed to bind on "
899 				    "all protocols for instance %s, "
900 				    "transitioning to degraded"),
901 				    instance->fmri);
902 				update_state(instance, IIS_DEGRADED, RERR_NONE);
903 				instance->bind_retries_exceeded = B_TRUE;
904 				break;
905 			}
906 
907 			destroy_bound_fds(instance);
908 			/*
909 			 * In the case we failed the 'bind' because set_pollfd()
910 			 * failed on all bound fds, use the offline handling.
911 			 */
912 			/* FALLTHROUGH */
913 		case IIS_OFFLINE:
914 		case IIS_OFFLINE_BIND:
915 			error_msg(gettext("Too many bind failures for instance "
916 			"%s, transitioning to maintenance"), instance->fmri);
917 			update_state(instance, IIS_MAINTENANCE,
918 			    RERR_FAULT);
919 			break;
920 		case IIS_IN_ONLINE_METHOD:
921 		case IIS_IN_REFRESH_METHOD:
922 			warn_msg(gettext("Failed to bind on all "
923 			    "protocols for instance %s, instance will go to "
924 			    "degraded"), instance->fmri);
925 			/*
926 			 * Set the retries exceeded flag so when the method
927 			 * completes the instance goes to the degraded state.
928 			 */
929 			instance->bind_retries_exceeded = B_TRUE;
930 			break;
931 		default:
932 #ifndef NDEBUG
933 			(void) fprintf(stderr,
934 			    "%s:%d: Unknown instance state %d.\n",
935 			    __FILE__, __LINE__, instance->cur_istate);
936 #endif
937 			abort();
938 		}
939 	} else if (instance->cur_istate == IIS_OFFLINE) {
940 		/*
941 		 * bind re-scheduled, so if we're offline reflect this in the
942 		 * state.
943 		 */
944 		update_state(instance, IIS_OFFLINE_BIND, RERR_NONE);
945 	}
946 }
947 
948 
949 /*
950  * Check if two transport protocols for RPC conflict.
951  */
952 
953 boolean_t
954 is_rpc_proto_conflict(const char *proto0, const char *proto1) {
955 	if (strcmp(proto0, "tcp") == 0) {
956 		if (strcmp(proto1, "tcp") == 0)
957 			return (B_TRUE);
958 		if (strcmp(proto1, "tcp6") == 0)
959 			return (B_TRUE);
960 		return (B_FALSE);
961 	}
962 
963 	if (strcmp(proto0, "tcp6") == 0) {
964 		if (strcmp(proto1, "tcp") == 0)
965 			return (B_TRUE);
966 		if (strcmp(proto1, "tcp6only") == 0)
967 			return (B_TRUE);
968 		if (strcmp(proto1, "tcp6") == 0)
969 			return (B_TRUE);
970 		return (B_FALSE);
971 	}
972 
973 	if (strcmp(proto0, "tcp6only") == 0) {
974 		if (strcmp(proto1, "tcp6only") == 0)
975 			return (B_TRUE);
976 		if (strcmp(proto1, "tcp6") == 0)
977 			return (B_TRUE);
978 		return (B_FALSE);
979 	}
980 
981 	if (strcmp(proto0, "udp") == 0) {
982 		if (strcmp(proto1, "udp") == 0)
983 			return (B_TRUE);
984 		if (strcmp(proto1, "udp6") == 0)
985 			return (B_TRUE);
986 		return (B_FALSE);
987 	}
988 
989 	if (strcmp(proto0, "udp6") == 0) {
990 
991 		if (strcmp(proto1, "udp") == 0)
992 			return (B_TRUE);
993 		if (strcmp(proto1, "udp6only") == 0)
994 			return (B_TRUE);
995 		if (strcmp(proto1, "udp6") == 0)
996 			return (B_TRUE);
997 		return (B_FALSE);
998 	}
999 
1000 	if (strcmp(proto0, "udp6only") == 0) {
1001 
1002 		if (strcmp(proto1, "udp6only") == 0)
1003 			return (B_TRUE);
1004 		if (strcmp(proto1, "udp6") == 0)
1005 			return (B_TRUE);
1006 		return (0);
1007 	}
1008 
1009 	/*
1010 	 * If the protocol isn't TCP/IP or UDP/IP assume that it has its own
1011 	 * port namepsace and that conflicts can be detected by literal string
1012 	 * comparison.
1013 	 */
1014 
1015 	if (strcmp(proto0, proto1))
1016 		return (FALSE);
1017 
1018 	return (B_TRUE);
1019 }
1020 
1021 
1022 /*
1023  * Check if inetd thinks this RPC program number is already registered.
1024  *
1025  * An RPC protocol conflict occurs if
1026  * 	a) the program numbers are the same and,
1027  * 	b) the version numbers overlap,
1028  * 	c) the protocols (TCP vs UDP vs tic*) are the same.
1029  */
1030 
1031 boolean_t
1032 is_rpc_num_in_use(int rpc_n, char *proto, int lowver, int highver) {
1033 	instance_t *i;
1034 	basic_cfg_t *cfg;
1035 	proto_info_t *pi;
1036 
1037 	for (i = uu_list_first(instance_list); i != NULL;
1038 	    i = uu_list_next(instance_list, i)) {
1039 
1040 		if (i->cur_istate != IIS_ONLINE)
1041 			continue;
1042 		cfg = i->config->basic;
1043 
1044 		for (pi = uu_list_first(cfg->proto_list); pi != NULL;
1045 		    pi = uu_list_next(cfg->proto_list, pi)) {
1046 
1047 			if (pi->ri == NULL)
1048 				continue;
1049 			if (pi->ri->prognum != rpc_n)
1050 				continue;
1051 			if (!is_rpc_proto_conflict(pi->proto, proto))
1052 				continue;
1053 			if ((lowver < pi->ri->lowver &&
1054 			    highver < pi->ri->lowver) ||
1055 			    (lowver > pi->ri->highver &&
1056 			    highver > pi->ri->highver))
1057 				continue;
1058 			return (B_TRUE);
1059 		}
1060 	}
1061 	return (B_FALSE);
1062 }
1063 
1064 
1065 /*
1066  * Independent of the transport, for each of the entries in the instance's
1067  * proto list this function first attempts to create an associated network fd;
1068  * for RPC services these are then bound to a kernel chosen port and the
1069  * fd is registered with rpcbind; for non-RPC services the fds are bound
1070  * to the port associated with the instance's service name. On any successful
1071  * binds the instance is taken online. Failed binds are handled by
1072  * handle_bind_failure().
1073  */
1074 void
1075 create_bound_fds(instance_t *instance)
1076 {
1077 	basic_cfg_t	*cfg = instance->config->basic;
1078 	boolean_t	failure = B_FALSE;
1079 	boolean_t	success = B_FALSE;
1080 	proto_info_t	*pi;
1081 
1082 	/*
1083 	 * Loop through and try and bind any unbound protos.
1084 	 */
1085 	for (pi = uu_list_first(cfg->proto_list); pi != NULL;
1086 	    pi = uu_list_next(cfg->proto_list, pi)) {
1087 		if (pi->listen_fd != -1)
1088 			continue;
1089 		if (cfg->istlx) {
1090 			pi->listen_fd = create_bound_endpoint(instance,
1091 			    (tlx_info_t *)pi);
1092 		} else {
1093 			/*
1094 			 * We cast pi to a void so we can then go on to cast
1095 			 * it to a socket_info_t without lint complaining
1096 			 * about alignment. This is done because the x86
1097 			 * version of lint thinks a lint suppression directive
1098 			 * is unnecessary and flags it as such, yet the sparc
1099 			 * version complains if it's absent.
1100 			 */
1101 			void *p = pi;
1102 			pi->listen_fd = create_bound_socket(instance,
1103 			    (socket_info_t *)p);
1104 		}
1105 		if (pi->listen_fd == -1) {
1106 			failure = B_TRUE;
1107 			continue;
1108 		}
1109 
1110 		if (pi->ri != NULL) {
1111 
1112 			/*
1113 			 * Don't register the same RPC program number twice.
1114 			 * Doing so silently discards the old service
1115 			 * without causing an error.
1116 			 */
1117 			if (is_rpc_num_in_use(pi->ri->prognum, pi->proto,
1118 			    pi->ri->lowver, pi->ri->highver)) {
1119 				failure = B_TRUE;
1120 				close_net_fd(instance, pi->listen_fd);
1121 				pi->listen_fd = -1;
1122 				continue;
1123 			}
1124 
1125 			unregister_rpc_service(instance->fmri, pi->ri);
1126 			if (register_rpc_service(instance->fmri, pi->ri) ==
1127 			    -1) {
1128 				close_net_fd(instance, pi->listen_fd);
1129 				pi->listen_fd = -1;
1130 				failure = B_TRUE;
1131 				continue;
1132 			}
1133 		}
1134 
1135 		success = B_TRUE;
1136 	}
1137 
1138 	switch (instance->cur_istate) {
1139 	case IIS_OFFLINE:
1140 	case IIS_OFFLINE_BIND:
1141 		/*
1142 		 * If we've managed to bind at least one proto lets run the
1143 		 * online method, so we can start listening for it.
1144 		 */
1145 		if (success && run_method(instance, IM_ONLINE, NULL) == -1)
1146 			return;	/* instance gone to maintenance */
1147 		break;
1148 	case IIS_ONLINE:
1149 	case IIS_IN_REFRESH_METHOD:
1150 		/*
1151 		 * We're 'online', so start polling on any bound fds we're
1152 		 * currently not.
1153 		 */
1154 		if (poll_bound_fds(instance, B_TRUE, NULL) != 0) {
1155 			failure = B_TRUE;
1156 		} else if (!failure) {
1157 			/*
1158 			 * We've successfully bound and poll'd upon all protos,
1159 			 * so reset the failure count.
1160 			 */
1161 			instance->bind_fail_count = 0;
1162 		}
1163 		break;
1164 	case IIS_IN_ONLINE_METHOD:
1165 		/*
1166 		 * Nothing to do here as the method completion code will start
1167 		 * listening for any successfully bound fds.
1168 		 */
1169 		break;
1170 	default:
1171 #ifndef NDEBUG
1172 		(void) fprintf(stderr, "%s:%d: Unknown instance state %d.\n",
1173 		    __FILE__, __LINE__, instance->cur_istate);
1174 #endif
1175 		abort();
1176 	}
1177 
1178 	if (failure)
1179 		handle_bind_failure(instance);
1180 }
1181 
1182 /*
1183  * Counter to create_bound_fds(), for each of the bound network fds this
1184  * function unregisters the instance from rpcbind if it's an RPC service,
1185  * stops listening for new connections for it and then closes the listening fd.
1186  */
1187 static void
1188 destroy_bound_fds(instance_t *instance)
1189 {
1190 	basic_cfg_t	*cfg = instance->config->basic;
1191 	proto_info_t	*pi;
1192 
1193 	for (pi = uu_list_first(cfg->proto_list); pi != NULL;
1194 	    pi = uu_list_next(cfg->proto_list, pi)) {
1195 		if (pi->listen_fd != -1) {
1196 			if (pi->ri != NULL)
1197 				unregister_rpc_service(instance->fmri, pi->ri);
1198 			clear_pollfd(pi->listen_fd);
1199 			close_net_fd(instance, pi->listen_fd);
1200 			pi->listen_fd = -1;
1201 		}
1202 	}
1203 
1204 	/* cancel any bind retries */
1205 	if (instance->bind_timer_id != -1)
1206 		cancel_bind_timer(instance);
1207 
1208 	instance->bind_retries_exceeded = B_FALSE;
1209 }
1210 
1211 /*
1212  * Perform %A address expansion and return a pointer to a static string
1213  * array containing crafted arguments. This expansion is provided for
1214  * compatibility with 4.2BSD daemons, and as such we've copied the logic of
1215  * the legacy inetd to maintain this compatibility as much as possible. This
1216  * logic is a bit scatty, but it dates back at least as far as SunOS 4.x.
1217  */
1218 static char **
1219 expand_address(instance_t *inst, const proto_info_t *pi)
1220 {
1221 	static char	addrbuf[sizeof ("ffffffff.65536")];
1222 	static char	*ret[3];
1223 	instance_cfg_t	*cfg = inst->config;
1224 	/*
1225 	 * We cast pi to a void so we can then go on to cast it to a
1226 	 * socket_info_t without lint complaining about alignment. This
1227 	 * is done because the x86 version of lint thinks a lint suppression
1228 	 * directive is unnecessary and flags it as such, yet the sparc
1229 	 * version complains if it's absent.
1230 	 */
1231 	const void	*p = pi;
1232 
1233 	/* set ret[0] to the basename of exec path */
1234 	if ((ret[0] = strrchr(cfg->methods[IM_START]->exec_path, '/'))
1235 	    != NULL) {
1236 		ret[0]++;
1237 	} else {
1238 		ret[0] = cfg->methods[IM_START]->exec_path;
1239 	}
1240 
1241 	if (!cfg->basic->istlx &&
1242 	    (((socket_info_t *)p)->type == SOCK_DGRAM)) {
1243 		ret[1] = NULL;
1244 	} else {
1245 		addrbuf[0] = '\0';
1246 		if (!cfg->basic->iswait &&
1247 		    (inst->remote_addr.ss_family == AF_INET)) {
1248 			struct sockaddr_in *sp;
1249 
1250 			sp = (struct sockaddr_in *)&(inst->remote_addr);
1251 			(void) snprintf(addrbuf, sizeof (addrbuf), "%x.%hu",
1252 			    ntohl(sp->sin_addr.s_addr), ntohs(sp->sin_port));
1253 		}
1254 		ret[1] = addrbuf;
1255 		ret[2] = NULL;
1256 	}
1257 
1258 	return (ret);
1259 }
1260 
1261 /*
1262  * Returns the state associated with the supplied method being run for an
1263  * instance.
1264  */
1265 static internal_inst_state_t
1266 get_method_state(instance_method_t method)
1267 {
1268 	state_info_t *sip;
1269 
1270 	for (sip = states; sip->istate != IIS_NONE; sip++) {
1271 		if (sip->method_running == method)
1272 			break;
1273 	}
1274 	assert(sip->istate != IIS_NONE);
1275 
1276 	return (sip->istate);
1277 }
1278 
1279 /*
1280  * Store the method's PID and CID in the repository. If the store fails
1281  * we ignore it and just drive on.
1282  */
1283 static void
1284 add_method_ids(instance_t *ins, pid_t pid, ctid_t cid, instance_method_t mthd)
1285 {
1286 	if (cid != -1)
1287 		(void) add_remove_contract(ins, B_TRUE, cid);
1288 
1289 	if (mthd == IM_START) {
1290 		if (add_rep_val(ins->start_pids, (int64_t)pid) == 0) {
1291 			(void) store_rep_vals(ins->start_pids, ins->fmri,
1292 			    PR_NAME_START_PIDS);
1293 		}
1294 	} else {
1295 		if (add_rep_val(ins->non_start_pid, (int64_t)pid) == 0) {
1296 			(void) store_rep_vals(ins->non_start_pid, ins->fmri,
1297 			    PR_NAME_NON_START_PID);
1298 		}
1299 	}
1300 }
1301 
1302 /*
1303  * Remove the method's PID and CID from the repository. If the removal
1304  * fails we ignore it and drive on.
1305  */
1306 void
1307 remove_method_ids(instance_t *inst, pid_t pid, ctid_t cid,
1308     instance_method_t mthd)
1309 {
1310 	if (cid != -1)
1311 		(void) add_remove_contract(inst, B_FALSE, cid);
1312 
1313 	if (mthd == IM_START) {
1314 		remove_rep_val(inst->start_pids, (int64_t)pid);
1315 		(void) store_rep_vals(inst->start_pids, inst->fmri,
1316 		    PR_NAME_START_PIDS);
1317 	} else {
1318 		remove_rep_val(inst->non_start_pid, (int64_t)pid);
1319 		(void) store_rep_vals(inst->non_start_pid, inst->fmri,
1320 		    PR_NAME_NON_START_PID);
1321 	}
1322 }
1323 
1324 static instance_t *
1325 create_instance(const char *fmri)
1326 {
1327 	instance_t *ret;
1328 
1329 	if (((ret = calloc(1, sizeof (instance_t))) == NULL) ||
1330 	    ((ret->fmri = strdup(fmri)) == NULL))
1331 		goto alloc_fail;
1332 
1333 	ret->conn_fd = -1;
1334 
1335 	ret->copies = 0;
1336 
1337 	ret->conn_rate_count = 0;
1338 	ret->fail_rate_count = 0;
1339 	ret->bind_fail_count = 0;
1340 
1341 	if (((ret->non_start_pid = create_rep_val_list()) == NULL) ||
1342 	    ((ret->start_pids = create_rep_val_list()) == NULL) ||
1343 	    ((ret->start_ctids = create_rep_val_list()) == NULL))
1344 		goto alloc_fail;
1345 
1346 	ret->cur_istate = IIS_NONE;
1347 	ret->next_istate = IIS_NONE;
1348 
1349 	if (((ret->cur_istate_rep = create_rep_val_list()) == NULL) ||
1350 	    ((ret->next_istate_rep = create_rep_val_list()) == NULL))
1351 		goto alloc_fail;
1352 
1353 	ret->config = NULL;
1354 	ret->new_config = NULL;
1355 
1356 	ret->timer_id = -1;
1357 	ret->bind_timer_id = -1;
1358 
1359 	ret->disable_req = B_FALSE;
1360 	ret->maintenance_req = B_FALSE;
1361 	ret->conn_rate_exceeded = B_FALSE;
1362 	ret->bind_retries_exceeded = B_FALSE;
1363 
1364 	ret->pending_rst_event = RESTARTER_EVENT_TYPE_INVALID;
1365 
1366 	return (ret);
1367 
1368 alloc_fail:
1369 	error_msg(strerror(errno));
1370 	destroy_instance(ret);
1371 	return (NULL);
1372 }
1373 
1374 static void
1375 destroy_instance(instance_t *inst)
1376 {
1377 	if (inst == NULL)
1378 		return;
1379 
1380 	destroy_instance_cfg(inst->config);
1381 	destroy_instance_cfg(inst->new_config);
1382 
1383 	destroy_rep_val_list(inst->cur_istate_rep);
1384 	destroy_rep_val_list(inst->next_istate_rep);
1385 
1386 	destroy_rep_val_list(inst->start_pids);
1387 	destroy_rep_val_list(inst->non_start_pid);
1388 	destroy_rep_val_list(inst->start_ctids);
1389 
1390 	free(inst->fmri);
1391 
1392 	free(inst);
1393 }
1394 
1395 /*
1396  * Retrieves the current and next states internal states. Returns 0 on success,
1397  * else returns one of the following on error:
1398  * SCF_ERROR_NO_MEMORY if memory allocation failed.
1399  * SCF_ERROR_CONNECTION_BROKEN if the connection to the repository was broken.
1400  * SCF_ERROR_TYPE_MISMATCH if the property was of an unexpected type.
1401  * SCF_ERROR_NO_RESOURCES if the server doesn't have adequate resources.
1402  * SCF_ERROR_NO_SERVER if the server isn't running.
1403  */
1404 static scf_error_t
1405 retrieve_instance_state(instance_t *inst)
1406 {
1407 	scf_error_t	ret;
1408 
1409 	/* retrieve internal states */
1410 	if (((ret = retrieve_rep_vals(inst->cur_istate_rep, inst->fmri,
1411 	    PR_NAME_CUR_INT_STATE)) != 0) ||
1412 	    ((ret = retrieve_rep_vals(inst->next_istate_rep, inst->fmri,
1413 	    PR_NAME_NEXT_INT_STATE)) != 0)) {
1414 		if (ret != SCF_ERROR_NOT_FOUND) {
1415 			error_msg(gettext(
1416 			    "Failed to read state of instance %s: %s"),
1417 			    inst->fmri, scf_strerror(scf_error()));
1418 			return (ret);
1419 		}
1420 
1421 		debug_msg("instance with no previous int state - "
1422 		    "setting state to uninitialized");
1423 
1424 		if ((set_single_rep_val(inst->cur_istate_rep,
1425 		    (int64_t)IIS_UNINITIALIZED) == -1) ||
1426 		    (set_single_rep_val(inst->next_istate_rep,
1427 		    (int64_t)IIS_NONE) == -1)) {
1428 			return (SCF_ERROR_NO_MEMORY);
1429 		}
1430 	}
1431 
1432 	/* update convenience states */
1433 	inst->cur_istate = get_single_rep_val(inst->cur_istate_rep);
1434 	inst->next_istate = get_single_rep_val(inst->next_istate_rep);
1435 	return (0);
1436 }
1437 
1438 /*
1439  * Retrieve stored process ids and register each of them so we process their
1440  * termination.
1441  */
1442 static int
1443 retrieve_method_pids(instance_t *inst)
1444 {
1445 	rep_val_t	*rv;
1446 
1447 	switch (retrieve_rep_vals(inst->start_pids, inst->fmri,
1448 	    PR_NAME_START_PIDS)) {
1449 	case 0:
1450 		break;
1451 	case SCF_ERROR_NOT_FOUND:
1452 		return (0);
1453 	default:
1454 		error_msg(gettext("Failed to retrieve the start pids of "
1455 		    "instance %s from repository: %s"), inst->fmri,
1456 		    scf_strerror(scf_error()));
1457 		return (-1);
1458 	}
1459 
1460 	rv = uu_list_first(inst->start_pids);
1461 	while (rv != NULL) {
1462 		if (register_method(inst, (pid_t)rv->val, (ctid_t)-1,
1463 		    IM_START, NULL) == 0) {
1464 			inst->copies++;
1465 			rv = uu_list_next(inst->start_pids, rv);
1466 		} else if (errno == ENOENT) {
1467 			pid_t pid = (pid_t)rv->val;
1468 
1469 			/*
1470 			 * The process must have already terminated. Remove
1471 			 * it from the list.
1472 			 */
1473 			rv = uu_list_next(inst->start_pids, rv);
1474 			remove_rep_val(inst->start_pids, pid);
1475 		} else {
1476 			error_msg(gettext("Failed to listen for the completion "
1477 			    "of %s method of instance %s"), START_METHOD_NAME,
1478 			    inst->fmri);
1479 			rv = uu_list_next(inst->start_pids, rv);
1480 		}
1481 	}
1482 
1483 	/* synch the repository pid list to remove any terminated pids */
1484 	(void) store_rep_vals(inst->start_pids, inst->fmri, PR_NAME_START_PIDS);
1485 
1486 	return (0);
1487 }
1488 
1489 /*
1490  * Remove the passed instance from inetd control.
1491  */
1492 static void
1493 remove_instance(instance_t *instance)
1494 {
1495 	switch (instance->cur_istate) {
1496 	case IIS_ONLINE:
1497 	case IIS_DEGRADED:
1498 		/* stop listening for network connections */
1499 		destroy_bound_fds(instance);
1500 		break;
1501 	case IIS_OFFLINE_BIND:
1502 		cancel_bind_timer(instance);
1503 		break;
1504 	case IIS_OFFLINE_CONRATE:
1505 		cancel_inst_timer(instance);
1506 		break;
1507 	}
1508 
1509 	/* stop listening for terminated methods */
1510 	unregister_instance_methods(instance);
1511 
1512 	uu_list_remove(instance_list, instance);
1513 	destroy_instance(instance);
1514 }
1515 
1516 /*
1517  * Refresh the configuration of instance 'inst'. This method gets called as
1518  * a result of a refresh event for the instance from the master restarter, so
1519  * we can rely upon the instance's running snapshot having been updated from
1520  * its configuration snapshot.
1521  */
1522 void
1523 refresh_instance(instance_t *inst)
1524 {
1525 	instance_cfg_t	*cfg;
1526 
1527 	switch (inst->cur_istate) {
1528 	case IIS_MAINTENANCE:
1529 	case IIS_DISABLED:
1530 	case IIS_UNINITIALIZED:
1531 		/*
1532 		 * Ignore any possible changes, we'll re-read the configuration
1533 		 * automatically when we exit these states.
1534 		 */
1535 		break;
1536 
1537 	case IIS_OFFLINE_COPIES:
1538 	case IIS_OFFLINE_BIND:
1539 	case IIS_OFFLINE:
1540 	case IIS_OFFLINE_CONRATE:
1541 		destroy_instance_cfg(inst->config);
1542 		if ((inst->config = read_instance_cfg(inst->fmri)) == NULL) {
1543 			log_invalid_cfg(inst->fmri);
1544 			if (inst->cur_istate == IIS_OFFLINE_BIND) {
1545 				cancel_bind_timer(inst);
1546 			} else if (inst->cur_istate == IIS_OFFLINE_CONRATE) {
1547 				cancel_inst_timer(inst);
1548 			}
1549 			update_state(inst, IIS_MAINTENANCE, RERR_FAULT);
1550 		} else {
1551 			switch (inst->cur_istate) {
1552 			case IIS_OFFLINE_BIND:
1553 				if (copies_limit_exceeded(inst)) {
1554 					/* Cancel scheduled bind retries. */
1555 					cancel_bind_timer(inst);
1556 
1557 					/*
1558 					 * Take the instance to the copies
1559 					 * offline state, via the offline
1560 					 * state.
1561 					 */
1562 					update_state(inst, IIS_OFFLINE,
1563 					    RERR_RESTART);
1564 					process_offline_inst(inst);
1565 				}
1566 				break;
1567 
1568 			case IIS_OFFLINE:
1569 				process_offline_inst(inst);
1570 				break;
1571 
1572 			case IIS_OFFLINE_CONRATE:
1573 				/*
1574 				 * Since we're already in a DOS state,
1575 				 * don't bother evaluating the copies
1576 				 * limit. This will be evaluated when
1577 				 * we leave this state in
1578 				 * process_offline_inst().
1579 				 */
1580 				break;
1581 
1582 			case IIS_OFFLINE_COPIES:
1583 				/*
1584 				 * Check if the copies limit has been increased
1585 				 * above the current count.
1586 				 */
1587 				if (!copies_limit_exceeded(inst)) {
1588 					update_state(inst, IIS_OFFLINE,
1589 					    RERR_RESTART);
1590 					process_offline_inst(inst);
1591 				}
1592 				break;
1593 
1594 			default:
1595 				assert(0);
1596 			}
1597 		}
1598 		break;
1599 
1600 	case IIS_DEGRADED:
1601 	case IIS_ONLINE:
1602 		if ((cfg = read_instance_cfg(inst->fmri)) != NULL) {
1603 			instance_cfg_t *ocfg = inst->config;
1604 
1605 			/*
1606 			 * Try to avoid the overhead of taking an instance
1607 			 * offline and back on again. We do this by limiting
1608 			 * this behavior to two eventualities:
1609 			 * - there needs to be a re-bind to listen on behalf
1610 			 *   of the instance with its new configuration. This
1611 			 *   could be because for example its service has been
1612 			 *   associated with a different port, or because the
1613 			 *   v6only protocol option has been newly applied to
1614 			 *   the instance.
1615 			 * - one or both of the start or online methods of the
1616 			 *   instance have changed in the new configuration.
1617 			 *   Without taking the instance offline when the
1618 			 *   start method changed the instance may be running
1619 			 *   with unwanted parameters (or event an unwanted
1620 			 *   binary); and without taking the instance offline
1621 			 *   if its online method was to change, some part of
1622 			 *   its running environment may have changed and would
1623 			 *   not be picked up until the instance next goes
1624 			 *   offline for another reason.
1625 			 */
1626 			if ((!bind_config_equal(ocfg->basic, cfg->basic)) ||
1627 			    !method_info_equal(ocfg->methods[IM_ONLINE],
1628 			    cfg->methods[IM_ONLINE]) ||
1629 			    !method_info_equal(ocfg->methods[IM_START],
1630 			    cfg->methods[IM_START])) {
1631 				destroy_bound_fds(inst);
1632 
1633 				assert(inst->new_config == NULL);
1634 				inst->new_config = cfg;
1635 
1636 				(void) run_method(inst, IM_OFFLINE, NULL);
1637 			} else {	/* no bind config / method changes */
1638 
1639 				/*
1640 				 * swap the proto list over from the old
1641 				 * configuration to the new, so we retain
1642 				 * our set of network fds.
1643 				 */
1644 				destroy_proto_list(cfg->basic);
1645 				cfg->basic->proto_list =
1646 				    ocfg->basic->proto_list;
1647 				ocfg->basic->proto_list = NULL;
1648 				destroy_instance_cfg(ocfg);
1649 				inst->config = cfg;
1650 
1651 				/* re-evaluate copies limits based on new cfg */
1652 				if (copies_limit_exceeded(inst)) {
1653 					destroy_bound_fds(inst);
1654 					(void) run_method(inst, IM_OFFLINE,
1655 					    NULL);
1656 				} else {
1657 					/*
1658 					 * Since the instance isn't being
1659 					 * taken offline, where we assume it
1660 					 * would pick-up any configuration
1661 					 * changes automatically when it goes
1662 					 * back online, run its refresh method
1663 					 * to allow it to pick-up any changes
1664 					 * whilst still online.
1665 					 */
1666 					(void) run_method(inst, IM_REFRESH,
1667 					    NULL);
1668 				}
1669 			}
1670 		} else {
1671 			log_invalid_cfg(inst->fmri);
1672 
1673 			destroy_bound_fds(inst);
1674 
1675 			inst->maintenance_req = B_TRUE;
1676 			(void) run_method(inst, IM_OFFLINE, NULL);
1677 		}
1678 		break;
1679 
1680 	default:
1681 		debug_msg("Unhandled current state %d for instance in "
1682 		    "refresh_instance", inst->cur_istate);
1683 		assert(0);
1684 	}
1685 }
1686 
1687 /*
1688  * Called by process_restarter_event() to handle a restarter event for an
1689  * instance.
1690  */
1691 static void
1692 handle_restarter_event(instance_t *instance, restarter_event_type_t event,
1693     boolean_t send_ack)
1694 {
1695 	switch (event) {
1696 	case RESTARTER_EVENT_TYPE_ADD_INSTANCE:
1697 		/*
1698 		 * When startd restarts, it sends _ADD_INSTANCE to delegated
1699 		 * restarters for all those services managed by them. We should
1700 		 * acknowledge this event, as startd's graph needs to be updated
1701 		 * about the current state of the service, when startd is
1702 		 * restarting.
1703 		 * update_state() is ok to be called here, as commands for
1704 		 * instances in transition are deferred by
1705 		 * process_restarter_event().
1706 		 */
1707 		update_state(instance, instance->cur_istate, RERR_NONE);
1708 		goto done;
1709 	case RESTARTER_EVENT_TYPE_ADMIN_REFRESH:
1710 		refresh_instance(instance);
1711 		goto done;
1712 	case RESTARTER_EVENT_TYPE_ADMIN_RESTART:
1713 		/*
1714 		 * We've got a restart event, so if the instance is online
1715 		 * in any way initiate taking it offline, and rely upon
1716 		 * our restarter to send us an online event to bring
1717 		 * it back online.
1718 		 */
1719 		switch (instance->cur_istate) {
1720 		case IIS_ONLINE:
1721 		case IIS_DEGRADED:
1722 			destroy_bound_fds(instance);
1723 			(void) run_method(instance, IM_OFFLINE, NULL);
1724 		}
1725 		goto done;
1726 	case RESTARTER_EVENT_TYPE_REMOVE_INSTANCE:
1727 		remove_instance(instance);
1728 		goto done;
1729 	case RESTARTER_EVENT_TYPE_STOP_RESET:
1730 	case RESTARTER_EVENT_TYPE_STOP:
1731 		switch (instance->cur_istate) {
1732 		case IIS_OFFLINE_CONRATE:
1733 		case IIS_OFFLINE_BIND:
1734 		case IIS_OFFLINE_COPIES:
1735 			/*
1736 			 * inetd must be closing down as we wouldn't get this
1737 			 * event in one of these states from the master
1738 			 * restarter. Take the instance to the offline resting
1739 			 * state.
1740 			 */
1741 			if (instance->cur_istate == IIS_OFFLINE_BIND) {
1742 				cancel_bind_timer(instance);
1743 			} else if (instance->cur_istate ==
1744 			    IIS_OFFLINE_CONRATE) {
1745 				cancel_inst_timer(instance);
1746 			}
1747 			update_state(instance, IIS_OFFLINE, RERR_RESTART);
1748 			goto done;
1749 		}
1750 		break;
1751 	}
1752 
1753 	switch (instance->cur_istate) {
1754 	case IIS_OFFLINE:
1755 		switch (event) {
1756 		case RESTARTER_EVENT_TYPE_START:
1757 			/*
1758 			 * Dependencies are met, let's take the service online.
1759 			 * Only try and bind for a wait type service if
1760 			 * no process is running on its behalf. Otherwise, just
1761 			 * mark the service online and binding will be attempted
1762 			 * when the process exits.
1763 			 */
1764 			if (!(instance->config->basic->iswait &&
1765 			    (uu_list_first(instance->start_pids) != NULL))) {
1766 				create_bound_fds(instance);
1767 			} else {
1768 				update_state(instance, IIS_ONLINE, RERR_NONE);
1769 			}
1770 			break;
1771 		case RESTARTER_EVENT_TYPE_DISABLE:
1772 		case RESTARTER_EVENT_TYPE_ADMIN_DISABLE:
1773 			/*
1774 			 * The instance should be disabled, so run the
1775 			 * instance's disabled method that will do the work
1776 			 * to take it there.
1777 			 */
1778 			(void) run_method(instance, IM_DISABLE, NULL);
1779 			break;
1780 		case RESTARTER_EVENT_TYPE_ADMIN_MAINT_ON:
1781 		case RESTARTER_EVENT_TYPE_DEPENDENCY_CYCLE:
1782 		case RESTARTER_EVENT_TYPE_INVALID_DEPENDENCY:
1783 			/*
1784 			 * The master restarter has requested the instance
1785 			 * go to maintenance; since we're already offline
1786 			 * just update the state to the maintenance state.
1787 			 */
1788 			update_state(instance, IIS_MAINTENANCE, RERR_RESTART);
1789 			break;
1790 		}
1791 		break;
1792 
1793 	case IIS_OFFLINE_BIND:
1794 		switch (event) {
1795 		case RESTARTER_EVENT_TYPE_DISABLE:
1796 		case RESTARTER_EVENT_TYPE_ADMIN_DISABLE:
1797 			/*
1798 			 * The instance should be disabled. Firstly, as for
1799 			 * the above dependencies unmet comment, cancel
1800 			 * the bind retry timer and update the state to
1801 			 * offline. Then, run the disable method to do the
1802 			 * work to take the instance from offline to
1803 			 * disabled.
1804 			 */
1805 			cancel_bind_timer(instance);
1806 			update_state(instance, IIS_OFFLINE, RERR_RESTART);
1807 			(void) run_method(instance, IM_DISABLE, NULL);
1808 			break;
1809 		case RESTARTER_EVENT_TYPE_ADMIN_MAINT_ON:
1810 		case RESTARTER_EVENT_TYPE_DEPENDENCY_CYCLE:
1811 		case RESTARTER_EVENT_TYPE_INVALID_DEPENDENCY:
1812 			/*
1813 			 * The master restarter has requested the instance
1814 			 * be placed in the maintenance state. Cancel the
1815 			 * outstanding retry timer, and since we're already
1816 			 * offline, update the state to maintenance.
1817 			 */
1818 			cancel_bind_timer(instance);
1819 			update_state(instance, IIS_MAINTENANCE, RERR_RESTART);
1820 			break;
1821 		}
1822 		break;
1823 
1824 	case IIS_DEGRADED:
1825 	case IIS_ONLINE:
1826 		switch (event) {
1827 		case RESTARTER_EVENT_TYPE_DISABLE:
1828 		case RESTARTER_EVENT_TYPE_ADMIN_DISABLE:
1829 			/*
1830 			 * The instance needs to be disabled. Do the same work
1831 			 * as for the dependencies unmet event below to
1832 			 * take the instance offline.
1833 			 */
1834 			destroy_bound_fds(instance);
1835 			/*
1836 			 * Indicate that the offline method is being run
1837 			 * as part of going to the disabled state, and to
1838 			 * carry on this transition.
1839 			 */
1840 			instance->disable_req = B_TRUE;
1841 			(void) run_method(instance, IM_OFFLINE, NULL);
1842 			break;
1843 		case RESTARTER_EVENT_TYPE_ADMIN_MAINT_ON:
1844 		case RESTARTER_EVENT_TYPE_DEPENDENCY_CYCLE:
1845 		case RESTARTER_EVENT_TYPE_INVALID_DEPENDENCY:
1846 			/*
1847 			 * The master restarter has requested the instance be
1848 			 * placed in the maintenance state. This involves
1849 			 * firstly taking the service offline, so do the
1850 			 * same work as for the dependencies unmet event
1851 			 * below. We set the maintenance_req flag to
1852 			 * indicate that when we get to the offline state
1853 			 * we should be placed directly into the maintenance
1854 			 * state.
1855 			 */
1856 			instance->maintenance_req = B_TRUE;
1857 			/* FALLTHROUGH */
1858 		case RESTARTER_EVENT_TYPE_STOP:
1859 			/*
1860 			 * Dependencies have become unmet. Close and
1861 			 * stop listening on the instance's network file
1862 			 * descriptor, and run the offline method to do
1863 			 * any work required to take us to the offline state.
1864 			 */
1865 			destroy_bound_fds(instance);
1866 			(void) run_method(instance, IM_OFFLINE, NULL);
1867 		}
1868 		break;
1869 
1870 	case IIS_UNINITIALIZED:
1871 		if (event == RESTARTER_EVENT_TYPE_DISABLE ||
1872 		    event == RESTARTER_EVENT_TYPE_ADMIN_DISABLE) {
1873 			update_state(instance, IIS_DISABLED, RERR_NONE);
1874 			break;
1875 		} else if (event != RESTARTER_EVENT_TYPE_ENABLE) {
1876 			/*
1877 			 * Ignore other events until we know whether we're
1878 			 * enabled or not.
1879 			 */
1880 			break;
1881 		}
1882 
1883 		/*
1884 		 * We've got an enabled event; make use of the handling in the
1885 		 * disable case.
1886 		 */
1887 		/* FALLTHROUGH */
1888 
1889 	case IIS_DISABLED:
1890 		switch (event) {
1891 		case RESTARTER_EVENT_TYPE_ENABLE:
1892 			/*
1893 			 * The instance needs enabling. Commence reading its
1894 			 * configuration and if successful place the instance
1895 			 * in the offline state and let process_offline_inst()
1896 			 * take it from there.
1897 			 */
1898 			destroy_instance_cfg(instance->config);
1899 			instance->config = read_instance_cfg(instance->fmri);
1900 			if (instance->config != NULL) {
1901 				update_state(instance, IIS_OFFLINE,
1902 				    RERR_RESTART);
1903 				process_offline_inst(instance);
1904 			} else {
1905 				log_invalid_cfg(instance->fmri);
1906 				update_state(instance, IIS_MAINTENANCE,
1907 				    RERR_RESTART);
1908 			}
1909 
1910 			break;
1911 		case RESTARTER_EVENT_TYPE_ADMIN_MAINT_ON:
1912 		case RESTARTER_EVENT_TYPE_DEPENDENCY_CYCLE:
1913 		case RESTARTER_EVENT_TYPE_INVALID_DEPENDENCY:
1914 			/*
1915 			 * The master restarter has requested the instance be
1916 			 * placed in the maintenance state, so just update its
1917 			 * state to maintenance.
1918 			 */
1919 			update_state(instance, IIS_MAINTENANCE, RERR_RESTART);
1920 			break;
1921 		}
1922 		break;
1923 
1924 	case IIS_MAINTENANCE:
1925 		switch (event) {
1926 		case RESTARTER_EVENT_TYPE_ADMIN_MAINT_OFF:
1927 		case RESTARTER_EVENT_TYPE_ADMIN_DISABLE:
1928 			/*
1929 			 * The master restarter has requested that the instance
1930 			 * be taken out of maintenance. Read its configuration,
1931 			 * and if successful place the instance in the offline
1932 			 * state and call process_offline_inst() to take it
1933 			 * from there.
1934 			 */
1935 			destroy_instance_cfg(instance->config);
1936 			instance->config = read_instance_cfg(instance->fmri);
1937 			if (instance->config != NULL) {
1938 				update_state(instance, IIS_OFFLINE,
1939 				    RERR_RESTART);
1940 				process_offline_inst(instance);
1941 			} else {
1942 				boolean_t enabled;
1943 
1944 				/*
1945 				 * The configuration was invalid. If the
1946 				 * service has disabled requested, let's
1947 				 * just place the instance in disabled even
1948 				 * though we haven't been able to run its
1949 				 * disable method, as the slightly incorrect
1950 				 * state is likely to be less of an issue to
1951 				 * an administrator than refusing to move an
1952 				 * instance to disabled. If disable isn't
1953 				 * requested, re-mark the service's state
1954 				 * as maintenance, so the administrator can
1955 				 * see the request was processed.
1956 				 */
1957 				if ((read_enable_merged(instance->fmri,
1958 				    &enabled) == 0) && !enabled) {
1959 					update_state(instance, IIS_DISABLED,
1960 					    RERR_RESTART);
1961 				} else {
1962 					log_invalid_cfg(instance->fmri);
1963 					update_state(instance, IIS_MAINTENANCE,
1964 					    RERR_FAULT);
1965 				}
1966 			}
1967 			break;
1968 		}
1969 		break;
1970 
1971 	case IIS_OFFLINE_CONRATE:
1972 		switch (event) {
1973 		case RESTARTER_EVENT_TYPE_DISABLE:
1974 			/*
1975 			 * The instance wants disabling. Take the instance
1976 			 * offline as for the dependencies unmet event above,
1977 			 * and then from there run the disable method to do
1978 			 * the work to take the instance to the disabled state.
1979 			 */
1980 			cancel_inst_timer(instance);
1981 			update_state(instance, IIS_OFFLINE, RERR_RESTART);
1982 			(void) run_method(instance, IM_DISABLE, NULL);
1983 			break;
1984 		case RESTARTER_EVENT_TYPE_ADMIN_MAINT_ON:
1985 		case RESTARTER_EVENT_TYPE_DEPENDENCY_CYCLE:
1986 		case RESTARTER_EVENT_TYPE_INVALID_DEPENDENCY:
1987 			/*
1988 			 * The master restarter has requested the instance
1989 			 * be taken to maintenance. Cancel the timer setup
1990 			 * when we entered this state, and go directly to
1991 			 * maintenance.
1992 			 */
1993 			cancel_inst_timer(instance);
1994 			update_state(instance, IIS_MAINTENANCE, RERR_RESTART);
1995 			break;
1996 		}
1997 		break;
1998 
1999 	case IIS_OFFLINE_COPIES:
2000 		switch (event) {
2001 		case RESTARTER_EVENT_TYPE_DISABLE:
2002 			/*
2003 			 * The instance wants disabling. Update the state
2004 			 * to offline, and run the disable method to do the
2005 			 * work to take it to the disabled state.
2006 			 */
2007 			update_state(instance, IIS_OFFLINE, RERR_RESTART);
2008 			(void) run_method(instance, IM_DISABLE, NULL);
2009 			break;
2010 		case RESTARTER_EVENT_TYPE_ADMIN_MAINT_ON:
2011 		case RESTARTER_EVENT_TYPE_DEPENDENCY_CYCLE:
2012 		case RESTARTER_EVENT_TYPE_INVALID_DEPENDENCY:
2013 			/*
2014 			 * The master restarter has requested the instance be
2015 			 * placed in maintenance. Since it's already offline
2016 			 * simply update the state.
2017 			 */
2018 			update_state(instance, IIS_MAINTENANCE, RERR_RESTART);
2019 			break;
2020 		}
2021 		break;
2022 
2023 	default:
2024 		debug_msg("handle_restarter_event: instance in an "
2025 		    "unexpected state");
2026 		assert(0);
2027 	}
2028 
2029 done:
2030 	if (send_ack)
2031 		ack_restarter_event(B_TRUE);
2032 }
2033 
2034 /*
2035  * Tries to read and process an event from the event pipe. If there isn't one
2036  * or an error occurred processing the event it returns -1. Else, if the event
2037  * is for an instance we're not already managing we read its state, add it to
2038  * our list to manage, and if appropriate read its configuration. Whether it's
2039  * new to us or not, we then handle the specific event.
2040  * Returns 0 if an event was read and processed successfully, else -1.
2041  */
2042 static int
2043 process_restarter_event(void)
2044 {
2045 	char			*fmri;
2046 	size_t			fmri_size;
2047 	restarter_event_type_t  event_type;
2048 	instance_t		*instance;
2049 	restarter_event_t	*event;
2050 	ssize_t			sz;
2051 
2052 	/*
2053 	 * Try to read an event pointer from the event pipe.
2054 	 */
2055 	errno = 0;
2056 	switch (safe_read(rst_event_pipe[PE_CONSUMER], &event,
2057 	    sizeof (event))) {
2058 	case 0:
2059 		break;
2060 	case  1:
2061 		if (errno == EAGAIN)	/* no event to read */
2062 			return (-1);
2063 
2064 		/* other end of pipe closed */
2065 
2066 		/* FALLTHROUGH */
2067 	default:			/* unexpected read error */
2068 		/*
2069 		 * There's something wrong with the event pipe. Let's
2070 		 * shutdown and be restarted.
2071 		 */
2072 		inetd_stop();
2073 		return (-1);
2074 	}
2075 
2076 	/*
2077 	 * Check if we're currently managing the instance which the event
2078 	 * pertains to. If not, read its complete state and add it to our
2079 	 * list to manage.
2080 	 */
2081 
2082 	fmri_size = scf_limit(SCF_LIMIT_MAX_FMRI_LENGTH);
2083 	if ((fmri = malloc(fmri_size)) == NULL) {
2084 		error_msg(strerror(errno));
2085 		goto fail;
2086 	}
2087 	sz = restarter_event_get_instance(event, fmri, fmri_size);
2088 	if (sz >= fmri_size)
2089 		assert(0);
2090 
2091 	for (instance = uu_list_first(instance_list); instance != NULL;
2092 	    instance = uu_list_next(instance_list, instance)) {
2093 		if (strcmp(instance->fmri, fmri) == 0)
2094 			break;
2095 	}
2096 
2097 	if (instance == NULL) {
2098 		int err;
2099 
2100 		debug_msg("New instance to manage: %s", fmri);
2101 
2102 		if (((instance = create_instance(fmri)) == NULL) ||
2103 		    (retrieve_instance_state(instance) != 0) ||
2104 		    (retrieve_method_pids(instance) != 0)) {
2105 			destroy_instance(instance);
2106 			free(fmri);
2107 			goto fail;
2108 		}
2109 
2110 		if (((err = iterate_repository_contracts(instance, 0))
2111 		    != 0) && (err != ENOENT)) {
2112 			error_msg(gettext(
2113 			    "Failed to adopt contracts of instance %s: %s"),
2114 			    instance->fmri, strerror(err));
2115 			destroy_instance(instance);
2116 			free(fmri);
2117 			goto fail;
2118 		}
2119 
2120 		uu_list_node_init(instance, &instance->link, instance_pool);
2121 		(void) uu_list_insert_after(instance_list, NULL, instance);
2122 
2123 		/*
2124 		 * Only read configuration for instances that aren't in any of
2125 		 * the disabled, maintenance or uninitialized states, since
2126 		 * they'll read it on state exit.
2127 		 */
2128 		if ((instance->cur_istate != IIS_DISABLED) &&
2129 		    (instance->cur_istate != IIS_MAINTENANCE) &&
2130 		    (instance->cur_istate != IIS_UNINITIALIZED)) {
2131 			instance->config = read_instance_cfg(instance->fmri);
2132 			if (instance->config == NULL) {
2133 				log_invalid_cfg(instance->fmri);
2134 				update_state(instance, IIS_MAINTENANCE,
2135 				    RERR_FAULT);
2136 			}
2137 		}
2138 	}
2139 
2140 	free(fmri);
2141 
2142 	event_type = restarter_event_get_type(event);
2143 	debug_msg("Event type: %d for instance: %s", event_type,
2144 	    instance->fmri);
2145 
2146 	/*
2147 	 * If the instance is currently running a method, don't process the
2148 	 * event now, but attach it to the instance for processing when
2149 	 * the instance finishes its transition.
2150 	 */
2151 	if (INST_IN_TRANSITION(instance)) {
2152 		debug_msg("storing event %d for instance %s", event_type,
2153 		    instance->fmri);
2154 		instance->pending_rst_event = event_type;
2155 	} else {
2156 		handle_restarter_event(instance, event_type, B_TRUE);
2157 	}
2158 
2159 	return (0);
2160 
2161 fail:
2162 	ack_restarter_event(B_FALSE);
2163 	return (-1);
2164 }
2165 
2166 /*
2167  * Do the state machine processing associated with the termination of instance
2168  * 'inst''s start method for the 'proto_name' protocol if this parameter is not
2169  * NULL.
2170  */
2171 void
2172 process_start_term(instance_t *inst, char *proto_name)
2173 {
2174 	basic_cfg_t	*cfg;
2175 
2176 	inst->copies--;
2177 
2178 	if ((inst->cur_istate == IIS_MAINTENANCE) ||
2179 	    (inst->cur_istate == IIS_DISABLED)) {
2180 		/* do any further processing/checks when we exit these states */
2181 		return;
2182 	}
2183 
2184 	cfg = inst->config->basic;
2185 
2186 	if (cfg->iswait) {
2187 		proto_info_t	*pi;
2188 		boolean_t	listen;
2189 
2190 		switch (inst->cur_istate) {
2191 		case IIS_ONLINE:
2192 		case IIS_DEGRADED:
2193 		case IIS_IN_REFRESH_METHOD:
2194 			/*
2195 			 * A wait type service's start method has exited.
2196 			 * Check if the method was fired off in this inetd's
2197 			 * lifetime, or a previous one; if the former,
2198 			 * re-commence listening on the service's behalf; if
2199 			 * the latter, mark the service offline and let bind
2200 			 * attempts commence.
2201 			 */
2202 			listen = B_FALSE;
2203 			for (pi = uu_list_first(cfg->proto_list); pi != NULL;
2204 			    pi = uu_list_next(cfg->proto_list, pi)) {
2205 				/*
2206 				 * If a bound fd exists, the method was fired
2207 				 * off during this inetd's lifetime.
2208 				 */
2209 				if (pi->listen_fd != -1) {
2210 					listen = B_TRUE;
2211 					if (proto_name == NULL ||
2212 					    strcmp(pi->proto, proto_name) == 0)
2213 						break;
2214 				}
2215 			}
2216 			if (pi != NULL) {
2217 				if (poll_bound_fds(inst, B_TRUE, proto_name) !=
2218 				    0)
2219 					handle_bind_failure(inst);
2220 			} else if (listen == B_FALSE) {
2221 				update_state(inst, IIS_OFFLINE, RERR_RESTART);
2222 				create_bound_fds(inst);
2223 			}
2224 		}
2225 	} else {
2226 		/*
2227 		 * Check if a nowait service should be brought back online
2228 		 * after exceeding its copies limit.
2229 		 */
2230 		if ((inst->cur_istate == IIS_OFFLINE_COPIES) &&
2231 		    !copies_limit_exceeded(inst)) {
2232 			update_state(inst, IIS_OFFLINE, RERR_NONE);
2233 			process_offline_inst(inst);
2234 		}
2235 	}
2236 }
2237 
2238 /*
2239  * If the instance has a pending event process it and initiate the
2240  * acknowledgement.
2241  */
2242 static void
2243 process_pending_rst_event(instance_t *inst)
2244 {
2245 	if (inst->pending_rst_event != RESTARTER_EVENT_TYPE_INVALID) {
2246 		restarter_event_type_t re;
2247 
2248 		debug_msg("Injecting pending event %d for instance %s",
2249 		    inst->pending_rst_event, inst->fmri);
2250 		re = inst->pending_rst_event;
2251 		inst->pending_rst_event = RESTARTER_EVENT_TYPE_INVALID;
2252 		handle_restarter_event(inst, re, B_TRUE);
2253 	}
2254 }
2255 
2256 /*
2257  * Do the state machine processing associated with the termination
2258  * of the specified instance's non-start method with the specified status.
2259  * Once the processing of the termination is done, the function also picks up
2260  * any processing that was blocked on the method running.
2261  */
2262 void
2263 process_non_start_term(instance_t *inst, int status)
2264 {
2265 	boolean_t ran_online_method = B_FALSE;
2266 
2267 	if (status == IMRET_FAILURE) {
2268 		error_msg(gettext("The %s method of instance %s failed, "
2269 		    "transitioning to maintenance"),
2270 		    methods[states[inst->cur_istate].method_running].name,
2271 		    inst->fmri);
2272 
2273 		if ((inst->cur_istate == IIS_IN_ONLINE_METHOD) ||
2274 		    (inst->cur_istate == IIS_IN_REFRESH_METHOD))
2275 			destroy_bound_fds(inst);
2276 
2277 		update_state(inst, IIS_MAINTENANCE, RERR_FAULT);
2278 
2279 		inst->maintenance_req = B_FALSE;
2280 		inst->conn_rate_exceeded = B_FALSE;
2281 
2282 		if (inst->new_config != NULL) {
2283 			destroy_instance_cfg(inst->new_config);
2284 			inst->new_config = NULL;
2285 		}
2286 
2287 		if (!inetd_stopping)
2288 			process_pending_rst_event(inst);
2289 
2290 		return;
2291 	}
2292 
2293 	/* non-failure method return */
2294 
2295 	if (status != IMRET_SUCCESS) {
2296 		/*
2297 		 * An instance method never returned a supported return code.
2298 		 * We'll assume this means the method succeeded for now whilst
2299 		 * non-GL-cognizant methods are used - eg. pkill.
2300 		 */
2301 		debug_msg("The %s method of instance %s returned "
2302 		    "non-compliant exit code: %d, assuming success",
2303 		    methods[states[inst->cur_istate].method_running].name,
2304 		    inst->fmri, status);
2305 	}
2306 
2307 	/*
2308 	 * Update the state from the in-transition state.
2309 	 */
2310 	switch (inst->cur_istate) {
2311 	case IIS_IN_ONLINE_METHOD:
2312 		ran_online_method = B_TRUE;
2313 		/* FALLTHROUGH */
2314 	case IIS_IN_REFRESH_METHOD:
2315 		/*
2316 		 * If we've exhausted the bind retries, flag that by setting
2317 		 * the instance's state to degraded.
2318 		 */
2319 		if (inst->bind_retries_exceeded) {
2320 			update_state(inst, IIS_DEGRADED, RERR_NONE);
2321 			break;
2322 		}
2323 		/* FALLTHROUGH */
2324 	default:
2325 		update_state(inst,
2326 		    methods[states[inst->cur_istate].method_running].dst_state,
2327 		    RERR_NONE);
2328 	}
2329 
2330 	if (inst->cur_istate == IIS_OFFLINE) {
2331 		if (inst->new_config != NULL) {
2332 			/*
2333 			 * This instance was found during refresh to need
2334 			 * taking offline because its newly read configuration
2335 			 * was sufficiently different. Now we're offline,
2336 			 * activate this new configuration.
2337 			 */
2338 			destroy_instance_cfg(inst->config);
2339 			inst->config = inst->new_config;
2340 			inst->new_config = NULL;
2341 		}
2342 
2343 		/* continue/complete any transitions that are in progress */
2344 		process_offline_inst(inst);
2345 
2346 	} else if (ran_online_method) {
2347 		/*
2348 		 * We've just successfully executed the online method. We have
2349 		 * a set of bound network fds that were created before running
2350 		 * this method, so now we're online start listening for
2351 		 * connections on them.
2352 		 */
2353 		if (poll_bound_fds(inst, B_TRUE, NULL) != 0)
2354 			handle_bind_failure(inst);
2355 	}
2356 
2357 	/*
2358 	 * If we're now out of transition (process_offline_inst() could have
2359 	 * fired off another method), carry out any jobs that were blocked by
2360 	 * us being in transition.
2361 	 */
2362 	if (!INST_IN_TRANSITION(inst)) {
2363 		if (inetd_stopping) {
2364 			if (!instance_stopped(inst)) {
2365 				/*
2366 				 * inetd is stopping, and this instance hasn't
2367 				 * been stopped. Inject a stop event.
2368 				 */
2369 				handle_restarter_event(inst,
2370 				    RESTARTER_EVENT_TYPE_STOP, B_FALSE);
2371 			}
2372 		} else {
2373 			process_pending_rst_event(inst);
2374 		}
2375 	}
2376 }
2377 
2378 /*
2379  * Check if configuration file specified is readable. If not return B_FALSE,
2380  * else return B_TRUE.
2381  */
2382 static boolean_t
2383 can_read_file(const char *path)
2384 {
2385 	int	ret;
2386 	int	serrno;
2387 
2388 	do {
2389 		ret = access(path, R_OK);
2390 	} while ((ret < 0) && (errno == EINTR));
2391 	if (ret < 0) {
2392 		if (errno != ENOENT) {
2393 			serrno = errno;
2394 			error_msg(gettext("Failed to access configuration "
2395 			    "file %s for performing modification checks: %s"),
2396 			    path, strerror(errno));
2397 			errno = serrno;
2398 		}
2399 		return (B_FALSE);
2400 	}
2401 	return (B_TRUE);
2402 }
2403 
2404 /*
2405  * Check whether the configuration file has changed contents since inetd
2406  * was last started/refreshed, and if so, log a message indicating that
2407  * inetconv needs to be run.
2408  */
2409 static void
2410 check_conf_file(void)
2411 {
2412 	char		*new_hash;
2413 	char		*old_hash = NULL;
2414 	scf_error_t	ret;
2415 	const char	*file;
2416 
2417 	if (conf_file == NULL) {
2418 		/*
2419 		 * No explicit config file specified, so see if one of the
2420 		 * default two are readable, checking the primary one first
2421 		 * followed by the secondary.
2422 		 */
2423 		if (can_read_file(PRIMARY_DEFAULT_CONF_FILE)) {
2424 			file = PRIMARY_DEFAULT_CONF_FILE;
2425 		} else if ((errno == ENOENT) &&
2426 		    can_read_file(SECONDARY_DEFAULT_CONF_FILE)) {
2427 			file = SECONDARY_DEFAULT_CONF_FILE;
2428 		} else {
2429 			return;
2430 		}
2431 	} else {
2432 		file = conf_file;
2433 		if (!can_read_file(file))
2434 			return;
2435 	}
2436 
2437 	if (calculate_hash(file, &new_hash) == 0) {
2438 		ret = retrieve_inetd_hash(&old_hash);
2439 		if (((ret == SCF_ERROR_NONE) &&
2440 		    (strcmp(old_hash, new_hash) != 0))) {
2441 			/* modified config file */
2442 			warn_msg(gettext(
2443 			    "Configuration file %s has been modified since "
2444 			    "inetconv was last run. \"inetconv -i %s\" must be "
2445 			    "run to apply any changes to the SMF"), file, file);
2446 		} else if ((ret != SCF_ERROR_NOT_FOUND) &&
2447 		    (ret != SCF_ERROR_NONE)) {
2448 			/* No message if hash not yet computed */
2449 			error_msg(gettext("Failed to check whether "
2450 			    "configuration file %s has been modified: %s"),
2451 			    file, scf_strerror(ret));
2452 		}
2453 		free(old_hash);
2454 		free(new_hash);
2455 	} else {
2456 		error_msg(gettext("Failed to check whether configuration file "
2457 		    "%s has been modified: %s"), file, strerror(errno));
2458 	}
2459 }
2460 
2461 /*
2462  * Refresh all inetd's managed instances and check the configuration file
2463  * for any updates since inetconv was last run, logging a message if there
2464  * are. We call the SMF refresh function to refresh each instance so that
2465  * the refresh request goes through the framework, and thus results in the
2466  * running snapshot of each instance being updated from the configuration
2467  * snapshot.
2468  */
2469 static void
2470 inetd_refresh(void)
2471 {
2472 	instance_t	*inst;
2473 
2474 	refresh_debug_flag();
2475 
2476 	/* call libscf to send refresh requests for all managed instances */
2477 	for (inst = uu_list_first(instance_list); inst != NULL;
2478 	    inst = uu_list_next(instance_list, inst)) {
2479 		if (smf_refresh_instance(inst->fmri) < 0) {
2480 			error_msg(gettext("Failed to refresh instance %s: %s"),
2481 			    inst->fmri, scf_strerror(scf_error()));
2482 		}
2483 	}
2484 
2485 	/*
2486 	 * Log a message if the configuration file has changed since inetconv
2487 	 * was last run.
2488 	 */
2489 	check_conf_file();
2490 }
2491 
2492 /*
2493  * Initiate inetd's shutdown.
2494  */
2495 static void
2496 inetd_stop(void)
2497 {
2498 	instance_t *inst;
2499 
2500 	/* Block handling signals for stop and refresh */
2501 	(void) sighold(SIGHUP);
2502 	(void) sighold(SIGTERM);
2503 
2504 	/* Indicate inetd is coming down */
2505 	inetd_stopping = B_TRUE;
2506 
2507 	/* Stop polling on restarter events. */
2508 	clear_pollfd(rst_event_pipe[PE_CONSUMER]);
2509 
2510 	/* Stop polling for any more stop/refresh requests. */
2511 	clear_pollfd(uds_fd);
2512 
2513 	/*
2514 	 * Send a stop event to all currently unstopped instances that
2515 	 * aren't in transition. For those that are in transition, the
2516 	 * event will get sent when the transition completes.
2517 	 */
2518 	for (inst = uu_list_first(instance_list); inst != NULL;
2519 	    inst = uu_list_next(instance_list, inst)) {
2520 		if (!instance_stopped(inst) && !INST_IN_TRANSITION(inst))
2521 			handle_restarter_event(inst,
2522 			    RESTARTER_EVENT_TYPE_STOP, B_FALSE);
2523 	}
2524 }
2525 
2526 /*
2527  * Sets up the intra-inetd-process Unix Domain Socket.
2528  * Returns -1 on error, else 0.
2529  */
2530 static int
2531 uds_init(void)
2532 {
2533 	struct sockaddr_un addr;
2534 
2535 	if ((uds_fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
2536 		error_msg("socket: %s", strerror(errno));
2537 		return (-1);
2538 	}
2539 
2540 	disable_blocking(uds_fd);
2541 
2542 	(void) unlink(INETD_UDS_PATH);  /* clean-up any stale files */
2543 
2544 	(void) memset(&addr, 0, sizeof (addr));
2545 	addr.sun_family = AF_UNIX;
2546 	/* CONSTCOND */
2547 	assert(sizeof (INETD_UDS_PATH) <= sizeof (addr.sun_path));
2548 	(void) strlcpy(addr.sun_path, INETD_UDS_PATH, sizeof (addr.sun_path));
2549 
2550 	if (bind(uds_fd, (struct sockaddr *)(&addr), sizeof (addr)) < 0) {
2551 		error_msg(gettext("Failed to bind socket to %s: %s"),
2552 		    INETD_UDS_PATH, strerror(errno));
2553 		(void) close(uds_fd);
2554 		return (-1);
2555 	}
2556 
2557 	(void) listen(uds_fd, UDS_BACKLOG);
2558 
2559 	if ((set_pollfd(uds_fd, POLLIN)) == -1) {
2560 		(void) close(uds_fd);
2561 		(void) unlink(INETD_UDS_PATH);
2562 		return (-1);
2563 	}
2564 
2565 	return (0);
2566 }
2567 
2568 static void
2569 uds_fini(void)
2570 {
2571 	if (uds_fd != -1)
2572 		(void) close(uds_fd);
2573 	(void) unlink(INETD_UDS_PATH);
2574 }
2575 
2576 /*
2577  * Handle an incoming request on the Unix Domain Socket. Returns -1 if there
2578  * was an error handling the event, else 0.
2579  */
2580 static int
2581 process_uds_event(void)
2582 {
2583 	uds_request_t		req;
2584 	int			fd;
2585 	struct sockaddr_un	addr;
2586 	socklen_t		len = sizeof (addr);
2587 	int			ret;
2588 	uint_t			retries = 0;
2589 	ucred_t			*ucred = NULL;
2590 	uid_t			euid;
2591 
2592 	do {
2593 		fd = accept(uds_fd, (struct sockaddr *)&addr, &len);
2594 	} while ((fd < 0) && (errno == EINTR));
2595 	if (fd < 0) {
2596 		if (errno != EWOULDBLOCK)
2597 			error_msg("accept failed: %s", strerror(errno));
2598 		return (-1);
2599 	}
2600 
2601 	if (getpeerucred(fd, &ucred) == -1) {
2602 		error_msg("getpeerucred failed: %s", strerror(errno));
2603 		(void) close(fd);
2604 		return (-1);
2605 	}
2606 
2607 	/* Check peer credentials before acting on the request */
2608 	euid = ucred_geteuid(ucred);
2609 	ucred_free(ucred);
2610 	if (euid != 0 && getuid() != euid) {
2611 		debug_msg("peer euid %u != uid %u",
2612 		    (uint_t)euid, (uint_t)getuid());
2613 		(void) close(fd);
2614 		return (-1);
2615 	}
2616 
2617 	for (retries = 0; retries < UDS_RECV_RETRIES; retries++) {
2618 		if (((ret = safe_read(fd, &req, sizeof (req))) != 1) ||
2619 		    (errno != EAGAIN))
2620 			break;
2621 
2622 		(void) poll(NULL, 0, 100);	/* 100ms pause */
2623 	}
2624 
2625 	if (ret != 0) {
2626 		error_msg(gettext("Failed read: %s"), strerror(errno));
2627 		(void) close(fd);
2628 		return (-1);
2629 	}
2630 
2631 	switch (req) {
2632 	case UR_REFRESH_INETD:
2633 		/* flag the request for event_loop() to process */
2634 		refresh_inetd_requested = B_TRUE;
2635 		(void) close(fd);
2636 		break;
2637 	case UR_STOP_INETD:
2638 		inetd_stop();
2639 		break;
2640 	default:
2641 		error_msg("unexpected UDS request");
2642 		(void) close(fd);
2643 		return (-1);
2644 	}
2645 
2646 	return (0);
2647 }
2648 
2649 /*
2650  * Perform checks for common exec string errors. We limit the checks to
2651  * whether the file exists, is a regular file, and has at least one execute
2652  * bit set. We leave the core security checks to exec() so as not to duplicate
2653  * and thus incur the associated drawbacks, but hope to catch the common
2654  * errors here.
2655  */
2656 static boolean_t
2657 passes_basic_exec_checks(const char *instance, const char *method,
2658     const char *path)
2659 {
2660 	struct stat	sbuf;
2661 
2662 	/* check the file exists */
2663 	while (stat(path, &sbuf) == -1) {
2664 		if (errno != EINTR) {
2665 			error_msg(gettext(
2666 			    "Can't stat the %s method of instance %s: %s"),
2667 			    method, instance, strerror(errno));
2668 			return (B_FALSE);
2669 		}
2670 	}
2671 
2672 	/*
2673 	 * Check if the file is a regular file and has at least one execute
2674 	 * bit set.
2675 	 */
2676 	if ((sbuf.st_mode & S_IFMT) != S_IFREG) {
2677 		error_msg(gettext(
2678 		    "The %s method of instance %s isn't a regular file"),
2679 		    method, instance);
2680 		return (B_FALSE);
2681 	} else if ((sbuf.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0) {
2682 		error_msg(gettext("The %s method instance %s doesn't have "
2683 		    "any execute permissions set"), method, instance);
2684 		return (B_FALSE);
2685 	}
2686 
2687 	return (B_TRUE);
2688 }
2689 
2690 static void
2691 exec_method(instance_t *instance, instance_method_t method, method_info_t *mi,
2692     struct method_context *mthd_ctxt, const proto_info_t *pi)
2693 {
2694 	char		**args;
2695 	char 		**env;
2696 	const char	*errf;
2697 	int		serrno;
2698 	basic_cfg_t	*cfg = instance->config->basic;
2699 
2700 	if (method == IM_START) {
2701 		/*
2702 		 * If wrappers checks fail, pretend the method was exec'd and
2703 		 * failed.
2704 		 */
2705 		if (!tcp_wrappers_ok(instance))
2706 			exit(IMRET_FAILURE);
2707 	}
2708 
2709 	/*
2710 	 * Revert the disposition of handled signals and ignored signals to
2711 	 * their defaults, unblocking any blocked ones as a side effect.
2712 	 */
2713 	(void) sigset(SIGHUP, SIG_DFL);
2714 	(void) sigset(SIGTERM, SIG_DFL);
2715 	(void) sigset(SIGINT, SIG_DFL);
2716 
2717 	/*
2718 	 * Setup exec arguments. Do this before the fd setup below, so our
2719 	 * logging related file fd doesn't get taken over before we call
2720 	 * expand_address().
2721 	 */
2722 	if ((method == IM_START) &&
2723 	    (strcmp(mi->exec_args_we.we_wordv[0], "%A") == 0)) {
2724 		args = expand_address(instance, pi);
2725 	} else {
2726 		args = mi->exec_args_we.we_wordv;
2727 	}
2728 
2729 	/* Generate audit trail for start operations */
2730 	if (method == IM_START) {
2731 		adt_event_data_t *ae;
2732 		struct sockaddr_storage ss;
2733 		priv_set_t *privset;
2734 		socklen_t sslen = sizeof (ss);
2735 
2736 		if ((ae = adt_alloc_event(audit_handle, ADT_inetd_connect))
2737 		    == NULL) {
2738 			error_msg(gettext("Unable to allocate audit event for "
2739 			    "the %s method of instance %s"),
2740 			    methods[method].name, instance->fmri);
2741 			exit(IMRET_FAILURE);
2742 		}
2743 
2744 		/*
2745 		 * The inetd_connect audit record consists of:
2746 		 *	Service name
2747 		 *	Execution path
2748 		 *	Remote address and port
2749 		 *	Local port
2750 		 *	Process privileges
2751 		 */
2752 		ae->adt_inetd_connect.service_name = cfg->svc_name;
2753 		ae->adt_inetd_connect.cmd = mi->exec_path;
2754 
2755 		if (instance->remote_addr.ss_family == AF_INET) {
2756 			struct in_addr *in = SS_SINADDR(instance->remote_addr);
2757 			ae->adt_inetd_connect.ip_adr[0] = in->s_addr;
2758 			ae->adt_inetd_connect.ip_type = ADT_IPv4;
2759 		} else {
2760 			uint32_t *addr6;
2761 			int i;
2762 
2763 			ae->adt_inetd_connect.ip_type = ADT_IPv6;
2764 			addr6 = (uint32_t *)SS_SINADDR(instance->remote_addr);
2765 			for (i = 0; i < 4; ++i)
2766 				ae->adt_inetd_connect.ip_adr[i] = addr6[i];
2767 		}
2768 
2769 		ae->adt_inetd_connect.ip_remote_port =
2770 		    ntohs(SS_PORT(instance->remote_addr));
2771 
2772 		if (getsockname(instance->conn_fd, (struct sockaddr *)&ss,
2773 		    &sslen) == 0)
2774 			ae->adt_inetd_connect.ip_local_port =
2775 			    ntohs(SS_PORT(ss));
2776 
2777 		privset = mthd_ctxt->priv_set;
2778 		if (privset == NULL) {
2779 			privset = priv_allocset();
2780 			if (privset != NULL &&
2781 			    getppriv(PRIV_EFFECTIVE, privset) != 0) {
2782 				priv_freeset(privset);
2783 				privset = NULL;
2784 			}
2785 		}
2786 
2787 		ae->adt_inetd_connect.privileges = privset;
2788 
2789 		(void) adt_put_event(ae, ADT_SUCCESS, ADT_SUCCESS);
2790 		adt_free_event(ae);
2791 
2792 		if (privset != NULL && mthd_ctxt->priv_set == NULL)
2793 			priv_freeset(privset);
2794 	}
2795 
2796 	/*
2797 	 * Set method context before the fd setup below so we can output an
2798 	 * error message if it fails.
2799 	 */
2800 	if ((errno = restarter_set_method_context(mthd_ctxt, &errf)) != 0) {
2801 		const char *msg;
2802 
2803 		if (errno == -1) {
2804 			if (strcmp(errf, "core_set_process_path") == 0) {
2805 				msg = gettext("Failed to set the corefile path "
2806 				    "for the %s method of instance %s");
2807 			} else if (strcmp(errf, "setproject") == 0) {
2808 				msg = gettext("Failed to assign a resource "
2809 				    "control for the %s method of instance %s");
2810 			} else if (strcmp(errf, "pool_set_binding") == 0) {
2811 				msg = gettext("Failed to bind the %s method of "
2812 				    "instance %s to a pool due to a system "
2813 				    "error");
2814 			} else {
2815 				assert(0);
2816 				abort();
2817 			}
2818 
2819 			error_msg(msg, methods[method].name, instance->fmri);
2820 
2821 			exit(IMRET_FAILURE);
2822 		}
2823 
2824 		if (errf != NULL && strcmp(errf, "pool_set_binding") == 0) {
2825 			switch (errno) {
2826 			case ENOENT:
2827 				msg = gettext("Failed to find resource pool "
2828 				    "for the %s method of instance %s");
2829 				break;
2830 
2831 			case EBADF:
2832 				msg = gettext("Failed to bind the %s method of "
2833 				    "instance %s to a pool due to invalid "
2834 				    "configuration");
2835 				break;
2836 
2837 			case EINVAL:
2838 				msg = gettext("Failed to bind the %s method of "
2839 				    "instance %s to a pool due to invalid "
2840 				    "pool name");
2841 				break;
2842 
2843 			default:
2844 				assert(0);
2845 				abort();
2846 			}
2847 
2848 			exit(IMRET_FAILURE);
2849 		}
2850 
2851 		if (errf != NULL) {
2852 			error_msg(gettext("Failed to set credentials for the "
2853 			    "%s method of instance %s (%s: %s)"),
2854 			    methods[method].name, instance->fmri, errf,
2855 			    strerror(errno));
2856 			exit(IMRET_FAILURE);
2857 		}
2858 
2859 		switch (errno) {
2860 		case ENOMEM:
2861 			msg = gettext("Failed to set credentials for the %s "
2862 			    "method of instance %s (out of memory)");
2863 			break;
2864 
2865 		case ENOENT:
2866 			msg = gettext("Failed to set credentials for the %s "
2867 			    "method of instance %s (no passwd or shadow "
2868 			    "entry for user)");
2869 			break;
2870 
2871 		default:
2872 			assert(0);
2873 			abort();
2874 		}
2875 
2876 		error_msg(msg, methods[method].name, instance->fmri);
2877 		exit(IMRET_FAILURE);
2878 	}
2879 
2880 	/* let exec() free mthd_ctxt */
2881 
2882 	/* setup standard fds */
2883 	if (method == IM_START) {
2884 		(void) dup2(instance->conn_fd, STDIN_FILENO);
2885 	} else {
2886 		(void) close(STDIN_FILENO);
2887 		(void) open("/dev/null", O_RDONLY);
2888 	}
2889 	(void) dup2(STDIN_FILENO, STDOUT_FILENO);
2890 	(void) dup2(STDIN_FILENO, STDERR_FILENO);
2891 
2892 	closefrom(STDERR_FILENO + 1);
2893 
2894 	method_preexec();
2895 
2896 	env = set_smf_env(mthd_ctxt, instance, methods[method].name);
2897 
2898 	if (env != NULL) {
2899 		do {
2900 			(void) execve(mi->exec_path, args, env);
2901 		} while (errno == EINTR);
2902 	}
2903 
2904 	serrno = errno;
2905 	/* start up logging again to report the error */
2906 	msg_init();
2907 	errno = serrno;
2908 
2909 	error_msg(
2910 	    gettext("Failed to exec %s method of instance %s: %s"),
2911 	    methods[method].name, instance->fmri, strerror(errno));
2912 
2913 	if ((method == IM_START) && (instance->config->basic->iswait)) {
2914 		/*
2915 		 * We couldn't exec the start method for a wait type service.
2916 		 * Eat up data from the endpoint, so that hopefully the
2917 		 * service's fd won't wake poll up on the next time round
2918 		 * event_loop(). This behavior is carried over from the old
2919 		 * inetd, and it seems somewhat arbitrary that it isn't
2920 		 * also done in the case of fork failures; but I guess
2921 		 * it assumes an exec failure is less likely to be the result
2922 		 * of a resource shortage, and is thus not worth retrying.
2923 		 */
2924 		consume_wait_data(instance, 0);
2925 	}
2926 
2927 	exit(IMRET_FAILURE);
2928 }
2929 
2930 static restarter_error_t
2931 get_method_error_success(instance_method_t method)
2932 {
2933 	switch (method) {
2934 	case IM_OFFLINE:
2935 		return (RERR_RESTART);
2936 	case IM_ONLINE:
2937 		return (RERR_RESTART);
2938 	case IM_DISABLE:
2939 		return (RERR_RESTART);
2940 	case IM_REFRESH:
2941 		return (RERR_REFRESH);
2942 	case IM_START:
2943 		return (RERR_RESTART);
2944 	}
2945 	(void) fprintf(stderr, gettext("Internal fatal error in inetd.\n"));
2946 
2947 	abort();
2948 	/* NOTREACHED */
2949 }
2950 
2951 static int
2952 smf_kill_process(instance_t *instance, int sig)
2953 {
2954 	rep_val_t	*rv;
2955 	int		ret = IMRET_SUCCESS;
2956 
2957 	/* Carry out process assassination */
2958 	for (rv = uu_list_first(instance->start_pids);
2959 	    rv != NULL;
2960 	    rv = uu_list_next(instance->start_pids, rv)) {
2961 		if ((kill((pid_t)rv->val, sig) != 0) &&
2962 		    (errno != ESRCH)) {
2963 			ret = IMRET_FAILURE;
2964 			error_msg(gettext("Unable to kill "
2965 			    "start process (%ld) of instance %s: %s"),
2966 			    rv->val, instance->fmri, strerror(errno));
2967 		}
2968 	}
2969 	return (ret);
2970 }
2971 
2972 /*
2973  * Runs the specified method of the specified service instance.
2974  * If the method was never specified, we handle it the same as if the
2975  * method was called and returned success, carrying on any transition the
2976  * instance may be in the midst of.
2977  * If the method isn't executable in its specified profile or an error occurs
2978  * forking a process to run the method in the function returns -1.
2979  * If a method binary is successfully executed, the function switches the
2980  * instance's cur state to the method's associated 'run' state and the next
2981  * state to the methods associated next state.
2982  * Returns -1 if there's an error before forking, else 0.
2983  */
2984 int
2985 run_method(instance_t *instance, instance_method_t method,
2986     const proto_info_t *start_info)
2987 {
2988 	pid_t			child_pid;
2989 	method_info_t		*mi;
2990 	struct method_context	*mthd_ctxt = NULL;
2991 	int			sig = 0;
2992 	int			ret;
2993 	instance_cfg_t		*cfg = instance->config;
2994 	ctid_t			cid;
2995 	boolean_t		trans_failure = B_TRUE;
2996 	int			serrno;
2997 
2998 	/*
2999 	 * Don't bother updating the instance's state for the start method
3000 	 * as there isn't a separate start method state.
3001 	 */
3002 	if (method != IM_START)
3003 		update_instance_states(instance, get_method_state(method),
3004 		    methods[method].dst_state,
3005 		    get_method_error_success(method));
3006 
3007 	if ((mi = cfg->methods[method]) == NULL) {
3008 		/*
3009 		 * If the absent method is IM_OFFLINE, default action needs
3010 		 * to be taken to avoid lingering processes which can prevent
3011 		 * the upcoming rebinding from happening.
3012 		 */
3013 		if ((method == IM_OFFLINE) && instance->config->basic->iswait) {
3014 			warn_msg(gettext("inetd_offline method for instance %s "
3015 			    "is unspecified.  Taking default action: kill."),
3016 			    instance->fmri);
3017 			(void) str2sig("TERM", &sig);
3018 			ret = smf_kill_process(instance, sig);
3019 			process_non_start_term(instance, ret);
3020 			return (0);
3021 		} else {
3022 			process_non_start_term(instance, IMRET_SUCCESS);
3023 			return (0);
3024 		}
3025 	}
3026 
3027 	/* Handle special method tokens, not allowed on start */
3028 	if (method != IM_START) {
3029 		if (restarter_is_null_method(mi->exec_path)) {
3030 			/* :true means nothing should be done */
3031 			process_non_start_term(instance, IMRET_SUCCESS);
3032 			return (0);
3033 		}
3034 
3035 		if ((sig = restarter_is_kill_method(mi->exec_path)) >= 0) {
3036 			/* Carry out contract assassination */
3037 			ret = iterate_repository_contracts(instance, sig);
3038 			/* ENOENT means we didn't find any contracts */
3039 			if (ret != 0 && ret != ENOENT) {
3040 				error_msg(gettext("Failed to send signal %d "
3041 				    "to contracts of instance %s: %s"), sig,
3042 				    instance->fmri, strerror(ret));
3043 				goto prefork_failure;
3044 			} else {
3045 				process_non_start_term(instance, IMRET_SUCCESS);
3046 				return (0);
3047 			}
3048 		}
3049 
3050 		if ((sig = restarter_is_kill_proc_method(mi->exec_path)) >= 0) {
3051 			ret = smf_kill_process(instance, sig);
3052 			process_non_start_term(instance, ret);
3053 			return (0);
3054 		}
3055 	}
3056 
3057 	/*
3058 	 * Get the associated method context before the fork so we can
3059 	 * modify the instances state if things go wrong.
3060 	 */
3061 	if ((mthd_ctxt = read_method_context(instance->fmri,
3062 	    methods[method].name, mi->exec_path)) == NULL)
3063 		goto prefork_failure;
3064 
3065 	/*
3066 	 * Perform some basic checks before we fork to limit the possibility
3067 	 * of exec failures, so we can modify the instance state if necessary.
3068 	 */
3069 	if (!passes_basic_exec_checks(instance->fmri, methods[method].name,
3070 	    mi->exec_path)) {
3071 		trans_failure = B_FALSE;
3072 		goto prefork_failure;
3073 	}
3074 
3075 	if (contract_prefork(instance->fmri, method) == -1)
3076 		goto prefork_failure;
3077 	child_pid = fork();
3078 	serrno = errno;
3079 	contract_postfork();
3080 
3081 	switch (child_pid) {
3082 	case -1:
3083 		error_msg(gettext(
3084 		    "Unable to fork %s method of instance %s: %s"),
3085 		    methods[method].name, instance->fmri, strerror(serrno));
3086 		if ((serrno != EAGAIN) && (serrno != ENOMEM))
3087 			trans_failure = B_FALSE;
3088 		goto prefork_failure;
3089 	case 0:				/* child */
3090 		exec_method(instance, method, mi, mthd_ctxt, start_info);
3091 		/* NOTREACHED */
3092 	default:			/* parent */
3093 		restarter_free_method_context(mthd_ctxt);
3094 		mthd_ctxt = NULL;
3095 
3096 		if (get_latest_contract(&cid) < 0)
3097 			cid = -1;
3098 
3099 		/*
3100 		 * Register this method so its termination is noticed and
3101 		 * the state transition this method participates in is
3102 		 * continued.
3103 		 */
3104 		if (register_method(instance, child_pid, cid, method,
3105 		    start_info->proto) != 0) {
3106 			/*
3107 			 * Since we will never find out about the termination
3108 			 * of this method, if it's a non-start method treat
3109 			 * is as a failure so we don't block restarter event
3110 			 * processing on it whilst it languishes in a method
3111 			 * running state.
3112 			 */
3113 			error_msg(gettext("Failed to monitor status of "
3114 			    "%s method of instance %s"), methods[method].name,
3115 			    instance->fmri);
3116 			if (method != IM_START)
3117 				process_non_start_term(instance, IMRET_FAILURE);
3118 		}
3119 
3120 		add_method_ids(instance, child_pid, cid, method);
3121 
3122 		/* do tcp tracing for those nowait instances that request it */
3123 		if ((method == IM_START) && cfg->basic->do_tcp_trace &&
3124 		    !cfg->basic->iswait) {
3125 			char buf[INET6_ADDRSTRLEN];
3126 
3127 			syslog(LOG_NOTICE, "%s[%d] from %s %d",
3128 			    cfg->basic->svc_name, child_pid,
3129 			    inet_ntop_native(instance->remote_addr.ss_family,
3130 			    SS_SINADDR(instance->remote_addr), buf,
3131 			    sizeof (buf)),
3132 			    ntohs(SS_PORT(instance->remote_addr)));
3133 		}
3134 	}
3135 
3136 	return (0);
3137 
3138 prefork_failure:
3139 	if (mthd_ctxt != NULL) {
3140 		restarter_free_method_context(mthd_ctxt);
3141 		mthd_ctxt = NULL;
3142 	}
3143 
3144 	if (method == IM_START) {
3145 		/*
3146 		 * Only place a start method in maintenance if we're sure
3147 		 * that the failure was non-transient.
3148 		 */
3149 		if (!trans_failure) {
3150 			destroy_bound_fds(instance);
3151 			update_state(instance, IIS_MAINTENANCE, RERR_FAULT);
3152 		}
3153 	} else {
3154 		/* treat the failure as if the method ran and failed */
3155 		process_non_start_term(instance, IMRET_FAILURE);
3156 	}
3157 
3158 	return (-1);
3159 }
3160 
3161 static int
3162 pending_connections(instance_t *instance, proto_info_t *pi)
3163 {
3164 	if (instance->config->basic->istlx) {
3165 		tlx_info_t *tl = (tlx_info_t *)pi;
3166 
3167 		return (uu_list_numnodes(tl->conn_ind_queue) != 0);
3168 	} else {
3169 		return (0);
3170 	}
3171 }
3172 
3173 static int
3174 accept_connection(instance_t *instance, proto_info_t *pi)
3175 {
3176 	int		fd;
3177 	socklen_t	size;
3178 
3179 	if (instance->config->basic->istlx) {
3180 		tlx_info_t *tl = (tlx_info_t *)pi;
3181 		tlx_pending_counter = \
3182 		    tlx_pending_counter - uu_list_numnodes(tl->conn_ind_queue);
3183 
3184 		fd = tlx_accept(instance->fmri, (tlx_info_t *)pi,
3185 		    &(instance->remote_addr));
3186 
3187 		tlx_pending_counter = \
3188 		    tlx_pending_counter + uu_list_numnodes(tl->conn_ind_queue);
3189 	} else {
3190 		size = sizeof (instance->remote_addr);
3191 		fd = accept(pi->listen_fd,
3192 		    (struct sockaddr *)&(instance->remote_addr), &size);
3193 		if (fd < 0)
3194 			error_msg("accept: %s", strerror(errno));
3195 	}
3196 
3197 	return (fd);
3198 }
3199 
3200 /*
3201  * Handle an incoming connection request for a nowait service.
3202  * This involves accepting the incoming connection on a new fd. Connection
3203  * rate checks are then performed, transitioning the service to the
3204  * conrate offline state if these fail. Otherwise, the service's start method
3205  * is run (performing TCP wrappers checks if applicable as we do), and on
3206  * success concurrent copies checking is done, transitioning the service to the
3207  * copies offline state if this fails.
3208  */
3209 static void
3210 process_nowait_request(instance_t *instance, proto_info_t *pi)
3211 {
3212 	basic_cfg_t		*cfg = instance->config->basic;
3213 	int			ret;
3214 	adt_event_data_t	*ae;
3215 	char			buf[BUFSIZ];
3216 
3217 	/* accept nowait service connections on a new fd */
3218 	if ((instance->conn_fd = accept_connection(instance, pi)) == -1) {
3219 		/*
3220 		 * Failed accept. Return and allow the event loop to initiate
3221 		 * another attempt later if the request is still present.
3222 		 */
3223 		return;
3224 	}
3225 
3226 	/*
3227 	 * Limit connection rate of nowait services. If either conn_rate_max
3228 	 * or conn_rate_offline are <= 0, no connection rate limit checking
3229 	 * is done. If the configured rate is exceeded, the instance is taken
3230 	 * to the connrate_offline state and a timer scheduled to try and
3231 	 * bring the instance back online after the configured offline time.
3232 	 */
3233 	if ((cfg->conn_rate_max > 0) && (cfg->conn_rate_offline > 0)) {
3234 		if (instance->conn_rate_count++ == 0) {
3235 			instance->conn_rate_start = time(NULL);
3236 		} else if (instance->conn_rate_count >
3237 		    cfg->conn_rate_max) {
3238 			time_t now = time(NULL);
3239 
3240 			if ((now - instance->conn_rate_start) > 1) {
3241 				instance->conn_rate_start = now;
3242 				instance->conn_rate_count = 1;
3243 			} else {
3244 				/* Generate audit record */
3245 				if ((ae = adt_alloc_event(audit_handle,
3246 				    ADT_inetd_ratelimit)) == NULL) {
3247 					error_msg(gettext("Unable to allocate "
3248 					    "rate limit audit event"));
3249 				} else {
3250 					adt_inetd_ratelimit_t *rl =
3251 					    &ae->adt_inetd_ratelimit;
3252 					/*
3253 					 * The inetd_ratelimit audit
3254 					 * record consists of:
3255 					 * 	Service name
3256 					 *	Connection rate limit
3257 					 */
3258 					rl->service_name = cfg->svc_name;
3259 					(void) snprintf(buf, sizeof (buf),
3260 					    "limit=%lld", cfg->conn_rate_max);
3261 					rl->limit = buf;
3262 					(void) adt_put_event(ae, ADT_SUCCESS,
3263 					    ADT_SUCCESS);
3264 					adt_free_event(ae);
3265 				}
3266 
3267 				error_msg(gettext(
3268 				    "Instance %s has exceeded its configured "
3269 				    "connection rate, additional connections "
3270 				    "will not be accepted for %d seconds"),
3271 				    instance->fmri, cfg->conn_rate_offline);
3272 
3273 				close_net_fd(instance, instance->conn_fd);
3274 				instance->conn_fd = -1;
3275 
3276 				destroy_bound_fds(instance);
3277 
3278 				instance->conn_rate_count = 0;
3279 
3280 				instance->conn_rate_exceeded = B_TRUE;
3281 				(void) run_method(instance, IM_OFFLINE, NULL);
3282 
3283 				return;
3284 			}
3285 		}
3286 	}
3287 
3288 	ret = run_method(instance, IM_START, pi);
3289 
3290 	close_net_fd(instance, instance->conn_fd);
3291 	instance->conn_fd = -1;
3292 
3293 	if (ret == -1) /* the method wasn't forked  */
3294 		return;
3295 
3296 	instance->copies++;
3297 
3298 	/*
3299 	 * Limit concurrent connections of nowait services.
3300 	 */
3301 	if (copies_limit_exceeded(instance)) {
3302 		/* Generate audit record */
3303 		if ((ae = adt_alloc_event(audit_handle, ADT_inetd_copylimit))
3304 		    == NULL) {
3305 			error_msg(gettext("Unable to allocate copy limit "
3306 			    "audit event"));
3307 		} else {
3308 			/*
3309 			 * The inetd_copylimit audit record consists of:
3310 			 *	Service name
3311 			 * 	Copy limit
3312 			 */
3313 			ae->adt_inetd_copylimit.service_name = cfg->svc_name;
3314 			(void) snprintf(buf, sizeof (buf), "limit=%lld",
3315 			    cfg->max_copies);
3316 			ae->adt_inetd_copylimit.limit = buf;
3317 			(void) adt_put_event(ae, ADT_SUCCESS, ADT_SUCCESS);
3318 			adt_free_event(ae);
3319 		}
3320 
3321 		warn_msg(gettext("Instance %s has reached its maximum "
3322 		    "configured copies, no new connections will be accepted"),
3323 		    instance->fmri);
3324 		destroy_bound_fds(instance);
3325 		(void) run_method(instance, IM_OFFLINE, NULL);
3326 	}
3327 }
3328 
3329 /*
3330  * Handle an incoming request for a wait type service.
3331  * Failure rate checking is done first, taking the service to the maintenance
3332  * state if the checks fail. Following this, the service's start method is run,
3333  * and on success, we stop listening for new requests for this service.
3334  */
3335 static void
3336 process_wait_request(instance_t *instance, const proto_info_t *pi)
3337 {
3338 	basic_cfg_t		*cfg = instance->config->basic;
3339 	int			ret;
3340 	adt_event_data_t	*ae;
3341 	char			buf[BUFSIZ];
3342 
3343 	instance->conn_fd = pi->listen_fd;
3344 
3345 	/*
3346 	 * Detect broken servers and transition them to maintenance. If a
3347 	 * wait type service exits without accepting the connection or
3348 	 * consuming (reading) the datagram, that service's descriptor will
3349 	 * select readable again, and inetd will fork another instance of
3350 	 * the server. If either wait_fail_cnt or wait_fail_interval are <= 0,
3351 	 * no failure rate detection is done.
3352 	 */
3353 	if ((cfg->wait_fail_cnt > 0) && (cfg->wait_fail_interval > 0)) {
3354 		if (instance->fail_rate_count++ == 0) {
3355 			instance->fail_rate_start = time(NULL);
3356 		} else if (instance->fail_rate_count > cfg->wait_fail_cnt) {
3357 			time_t now = time(NULL);
3358 
3359 			if ((now - instance->fail_rate_start) >
3360 			    cfg->wait_fail_interval) {
3361 				instance->fail_rate_start = now;
3362 				instance->fail_rate_count = 1;
3363 			} else {
3364 				/* Generate audit record */
3365 				if ((ae = adt_alloc_event(audit_handle,
3366 				    ADT_inetd_failrate)) == NULL) {
3367 					error_msg(gettext("Unable to allocate "
3368 					    "failure rate audit event"));
3369 				} else {
3370 					adt_inetd_failrate_t *fr =
3371 					    &ae->adt_inetd_failrate;
3372 					/*
3373 					 * The inetd_failrate audit record
3374 					 * consists of:
3375 					 * 	Service name
3376 					 * 	Failure rate
3377 					 *	Interval
3378 					 * Last two are expressed as k=v pairs
3379 					 * in the values field.
3380 					 */
3381 					fr->service_name = cfg->svc_name;
3382 					(void) snprintf(buf, sizeof (buf),
3383 					    "limit=%lld,interval=%d",
3384 					    cfg->wait_fail_cnt,
3385 					    cfg->wait_fail_interval);
3386 					fr->values = buf;
3387 					(void) adt_put_event(ae, ADT_SUCCESS,
3388 					    ADT_SUCCESS);
3389 					adt_free_event(ae);
3390 				}
3391 
3392 				error_msg(gettext(
3393 				    "Instance %s has exceeded its configured "
3394 				    "failure rate, transitioning to "
3395 				    "maintenance"), instance->fmri);
3396 				instance->fail_rate_count = 0;
3397 
3398 				destroy_bound_fds(instance);
3399 
3400 				instance->maintenance_req = B_TRUE;
3401 				(void) run_method(instance, IM_OFFLINE, NULL);
3402 				return;
3403 			}
3404 		}
3405 	}
3406 
3407 	ret = run_method(instance, IM_START, pi);
3408 
3409 	instance->conn_fd = -1;
3410 
3411 	if (ret == 0) {
3412 		/*
3413 		 * Stop listening for connections now we've fired off the
3414 		 * server for a wait type instance.
3415 		 */
3416 		(void) poll_bound_fds(instance, B_FALSE, pi->proto);
3417 	}
3418 }
3419 
3420 /*
3421  * Process any networks requests for each proto for each instance.
3422  */
3423 void
3424 process_network_events(void)
3425 {
3426 	instance_t	*instance;
3427 
3428 	for (instance = uu_list_first(instance_list); instance != NULL;
3429 	    instance = uu_list_next(instance_list, instance)) {
3430 		basic_cfg_t	*cfg;
3431 		proto_info_t	*pi;
3432 
3433 		/*
3434 		 * Ignore instances in states that definitely don't have any
3435 		 * listening fds.
3436 		 */
3437 		switch (instance->cur_istate) {
3438 		case IIS_ONLINE:
3439 		case IIS_DEGRADED:
3440 		case IIS_IN_REFRESH_METHOD:
3441 			break;
3442 		default:
3443 			continue;
3444 		}
3445 
3446 		cfg = instance->config->basic;
3447 
3448 		for (pi = uu_list_first(cfg->proto_list); pi != NULL;
3449 		    pi = uu_list_next(cfg->proto_list, pi)) {
3450 			if (((pi->listen_fd != -1) &&
3451 			    isset_pollfd(pi->listen_fd)) ||
3452 			    pending_connections(instance, pi)) {
3453 				if (cfg->iswait) {
3454 					process_wait_request(instance, pi);
3455 				} else {
3456 					process_nowait_request(instance, pi);
3457 				}
3458 			}
3459 		}
3460 	}
3461 }
3462 
3463 /* ARGSUSED0 */
3464 static void
3465 sigterm_handler(int sig)
3466 {
3467 	got_sigterm = B_TRUE;
3468 }
3469 
3470 /* ARGSUSED0 */
3471 static void
3472 sighup_handler(int sig)
3473 {
3474 	refresh_inetd_requested = B_TRUE;
3475 }
3476 
3477 /*
3478  * inetd's major work loop. This function sits in poll waiting for events
3479  * to occur, processing them when they do. The possible events are
3480  * master restarter requests, expired timer queue timers, stop/refresh signal
3481  * requests, contract events indicating process termination, stop/refresh
3482  * requests originating from one of the stop/refresh inetd processes and
3483  * network events.
3484  * The loop is exited when a stop request is received and processed, and
3485  * all the instances have reached a suitable 'stopping' state.
3486  */
3487 static void
3488 event_loop(void)
3489 {
3490 	instance_t		*instance;
3491 	int			timeout;
3492 
3493 	for (;;) {
3494 		int	pret = -1;
3495 
3496 		if (tlx_pending_counter != 0)
3497 			timeout = 0;
3498 		else
3499 			timeout = iu_earliest_timer(timer_queue);
3500 
3501 		if (!got_sigterm && !refresh_inetd_requested) {
3502 			pret = poll(poll_fds, num_pollfds, timeout);
3503 			if ((pret == -1) && (errno != EINTR)) {
3504 				error_msg(gettext("poll failure: %s"),
3505 				    strerror(errno));
3506 				continue;
3507 			}
3508 		}
3509 
3510 		if (got_sigterm) {
3511 			msg_fini();
3512 			inetd_stop();
3513 			got_sigterm = B_FALSE;
3514 			goto check_if_stopped;
3515 		}
3516 
3517 		/*
3518 		 * Process any stop/refresh requests from the Unix Domain
3519 		 * Socket.
3520 		 */
3521 		if ((pret != -1) && isset_pollfd(uds_fd)) {
3522 			while (process_uds_event() == 0)
3523 				;
3524 		}
3525 
3526 		/*
3527 		 * Process refresh request. We do this check after the UDS
3528 		 * event check above, as it would be wasted processing if we
3529 		 * started refreshing inetd based on a SIGHUP, and then were
3530 		 * told to shut-down via a UDS event.
3531 		 */
3532 		if (refresh_inetd_requested) {
3533 			refresh_inetd_requested = B_FALSE;
3534 			if (!inetd_stopping)
3535 				inetd_refresh();
3536 		}
3537 
3538 		/*
3539 		 * We were interrupted by a signal. Don't waste any more
3540 		 * time processing a potentially inaccurate poll return.
3541 		 */
3542 		if (pret == -1)
3543 			continue;
3544 
3545 		/*
3546 		 * Process any instance restarter events.
3547 		 */
3548 		if (isset_pollfd(rst_event_pipe[PE_CONSUMER])) {
3549 			while (process_restarter_event() == 0)
3550 				;
3551 		}
3552 
3553 		/*
3554 		 * Process any expired timers (bind retry, con-rate offline,
3555 		 * method timeouts).
3556 		 */
3557 		(void) iu_expire_timers(timer_queue);
3558 
3559 		process_terminated_methods();
3560 
3561 		/*
3562 		 * If inetd is stopping, check whether all our managed
3563 		 * instances have been stopped and we can return.
3564 		 */
3565 		if (inetd_stopping) {
3566 check_if_stopped:
3567 			for (instance = uu_list_first(instance_list);
3568 			    instance != NULL;
3569 			    instance = uu_list_next(instance_list, instance)) {
3570 				if (!instance_stopped(instance)) {
3571 					debug_msg("%s not yet stopped",
3572 					    instance->fmri);
3573 					break;
3574 				}
3575 			}
3576 			/* if all instances are stopped, return */
3577 			if (instance == NULL)
3578 				return;
3579 		}
3580 
3581 		process_network_events();
3582 	}
3583 }
3584 
3585 static void
3586 fini(void)
3587 {
3588 	method_fini();
3589 	uds_fini();
3590 	if (timer_queue != NULL)
3591 		iu_tq_destroy(timer_queue);
3592 
3593 
3594 	/*
3595 	 * We don't bother to undo the restarter interface at all.
3596 	 * Because of quirks in the interface, there is no way to
3597 	 * disconnect from the channel and cause any new events to be
3598 	 * queued.  However, any events which are received and not
3599 	 * acknowledged will be re-sent when inetd restarts as long as inetd
3600 	 * uses the same subscriber ID, which it does.
3601 	 *
3602 	 * By keeping the event pipe open but ignoring it, any events which
3603 	 * occur will cause restarter_event_proxy to hang without breaking
3604 	 * anything.
3605 	 */
3606 
3607 	if (instance_list != NULL) {
3608 		void		*cookie = NULL;
3609 		instance_t	*inst;
3610 
3611 		while ((inst = uu_list_teardown(instance_list, &cookie)) !=
3612 		    NULL)
3613 			destroy_instance(inst);
3614 		uu_list_destroy(instance_list);
3615 	}
3616 	if (instance_pool != NULL)
3617 		uu_list_pool_destroy(instance_pool);
3618 	tlx_fini();
3619 	config_fini();
3620 	repval_fini();
3621 	poll_fini();
3622 
3623 	/* Close audit session */
3624 	(void) adt_end_session(audit_handle);
3625 }
3626 
3627 static int
3628 init(void)
3629 {
3630 	int err;
3631 
3632 	if (repval_init() < 0)
3633 		goto failed;
3634 
3635 	if (config_init() < 0)
3636 		goto failed;
3637 
3638 	refresh_debug_flag();
3639 
3640 	if (tlx_init() < 0)
3641 		goto failed;
3642 
3643 	/* Setup instance list. */
3644 	if ((instance_pool = uu_list_pool_create("instance_pool",
3645 	    sizeof (instance_t), offsetof(instance_t, link), NULL,
3646 	    UU_LIST_POOL_DEBUG)) == NULL) {
3647 		error_msg("%s: %s",
3648 		    gettext("Failed to create instance pool"),
3649 		    uu_strerror(uu_error()));
3650 		goto failed;
3651 	}
3652 	if ((instance_list = uu_list_create(instance_pool, NULL, 0)) == NULL) {
3653 		error_msg("%s: %s",
3654 		    gettext("Failed to create instance list"),
3655 		    uu_strerror(uu_error()));
3656 		goto failed;
3657 	}
3658 
3659 	/*
3660 	 * Create event pipe to communicate events with the main event
3661 	 * loop and add it to the event loop's fdset.
3662 	 */
3663 	if (pipe(rst_event_pipe) < 0) {
3664 		error_msg("pipe: %s", strerror(errno));
3665 		goto failed;
3666 	}
3667 	/*
3668 	 * We only leave the producer end to block on reads/writes as we
3669 	 * can't afford to block in the main thread, yet need to in
3670 	 * the restarter event thread, so it can sit and wait for an
3671 	 * acknowledgement to be written to the pipe.
3672 	 */
3673 	disable_blocking(rst_event_pipe[PE_CONSUMER]);
3674 	if ((set_pollfd(rst_event_pipe[PE_CONSUMER], POLLIN)) == -1)
3675 		goto failed;
3676 
3677 	/*
3678 	 * Register with master restarter for managed service events. This
3679 	 * will fail, amongst other reasons, if inetd is already running.
3680 	 */
3681 	if ((err = restarter_bind_handle(RESTARTER_EVENT_VERSION,
3682 	    INETD_INSTANCE_FMRI, restarter_event_proxy, 0,
3683 	    &rst_event_handle)) != 0) {
3684 		error_msg(gettext(
3685 		    "Failed to register for restarter events: %s"),
3686 		    strerror(err));
3687 		goto failed;
3688 	}
3689 
3690 	if (contract_init() < 0)
3691 		goto failed;
3692 
3693 	if ((timer_queue = iu_tq_create()) == NULL) {
3694 		error_msg(gettext("Failed to create timer queue."));
3695 		goto failed;
3696 	}
3697 
3698 	if (uds_init() < 0)
3699 		goto failed;
3700 
3701 	if (method_init() < 0)
3702 		goto failed;
3703 
3704 	/* Initialize auditing session */
3705 	if (adt_start_session(&audit_handle, NULL, ADT_USE_PROC_DATA) != 0) {
3706 		error_msg(gettext("Unable to start audit session"));
3707 	}
3708 
3709 	/*
3710 	 * Initialize signal dispositions/masks
3711 	 */
3712 	(void) sigset(SIGHUP, sighup_handler);
3713 	(void) sigset(SIGTERM, sigterm_handler);
3714 	(void) sigignore(SIGINT);
3715 
3716 	return (0);
3717 
3718 failed:
3719 	fini();
3720 	return (-1);
3721 }
3722 
3723 static int
3724 start_method(void)
3725 {
3726 	int	i;
3727 	int	pipe_fds[2];
3728 	int	child;
3729 
3730 	/* Create pipe for child to notify parent of initialization success. */
3731 	if (pipe(pipe_fds) < 0) {
3732 		error_msg("pipe: %s", strerror(errno));
3733 		return (SMF_EXIT_ERR_OTHER);
3734 	}
3735 
3736 	if ((child = fork()) == -1) {
3737 		error_msg("fork: %s", strerror(errno));
3738 		(void) close(pipe_fds[PE_CONSUMER]);
3739 		(void) close(pipe_fds[PE_PRODUCER]);
3740 		return (SMF_EXIT_ERR_OTHER);
3741 	} else if (child > 0) {			/* parent */
3742 
3743 		/* Wait on child to return success of initialization. */
3744 		(void) close(pipe_fds[PE_PRODUCER]);
3745 		if ((safe_read(pipe_fds[PE_CONSUMER], &i, sizeof (i)) != 0) ||
3746 		    (i < 0)) {
3747 			error_msg(gettext(
3748 			    "Initialization failed, unable to start"));
3749 			(void) close(pipe_fds[PE_CONSUMER]);
3750 			/*
3751 			 * Batch all initialization errors as 'other' errors,
3752 			 * resulting in retries being attempted.
3753 			 */
3754 			return (SMF_EXIT_ERR_OTHER);
3755 		} else {
3756 			(void) close(pipe_fds[PE_CONSUMER]);
3757 			return (SMF_EXIT_OK);
3758 		}
3759 	} else {				/* child */
3760 		/*
3761 		 * Perform initialization and return success code down
3762 		 * the pipe.
3763 		 */
3764 		(void) close(pipe_fds[PE_CONSUMER]);
3765 		i = init();
3766 		if ((safe_write(pipe_fds[PE_PRODUCER], &i, sizeof (i)) < 0) ||
3767 		    (i < 0)) {
3768 			error_msg(gettext("pipe write failure: %s"),
3769 			    strerror(errno));
3770 			exit(1);
3771 		}
3772 		(void) close(pipe_fds[PE_PRODUCER]);
3773 
3774 		(void) setsid();
3775 
3776 		/*
3777 		 * Log a message if the configuration file has changed since
3778 		 * inetconv was last run.
3779 		 */
3780 		check_conf_file();
3781 
3782 		event_loop();
3783 
3784 		fini();
3785 		debug_msg("inetd stopped");
3786 		msg_fini();
3787 		exit(0);
3788 	}
3789 	/* NOTREACHED */
3790 }
3791 
3792 /*
3793  * When inetd is run from outside the SMF, this message is output to provide
3794  * the person invoking inetd with further information that will help them
3795  * understand how to start and stop inetd, and to achieve the other
3796  * behaviors achievable with the legacy inetd command line interface, if
3797  * it is possible.
3798  */
3799 static void
3800 legacy_usage(void)
3801 {
3802 	(void) fprintf(stderr,
3803 	    "inetd is now an smf(5) managed service and can no longer be run "
3804 	    "from the\n"
3805 	    "command line. To enable or disable inetd refer to svcadm(1M) on\n"
3806 	    "how to enable \"%s\", the inetd instance.\n"
3807 	    "\n"
3808 	    "The traditional inetd command line option mappings are:\n"
3809 	    "\t-d : there is no supported debug output\n"
3810 	    "\t-s : inetd is only runnable from within the SMF\n"
3811 	    "\t-t : See inetadm(1M) on how to enable TCP tracing\n"
3812 	    "\t-r : See inetadm(1M) on how to set a failure rate\n"
3813 	    "\n"
3814 	    "To specify an alternative configuration file see svccfg(1M)\n"
3815 	    "for how to modify the \"%s/%s\" string type property of\n"
3816 	    "the inetd instance, and modify it according to the syntax:\n"
3817 	    "\"%s [alt_config_file] %%m\".\n"
3818 	    "\n"
3819 	    "For further information on inetd see inetd(1M).\n",
3820 	    INETD_INSTANCE_FMRI, START_METHOD_ARG, SCF_PROPERTY_EXEC,
3821 	    INETD_PATH);
3822 }
3823 
3824 /*
3825  * Usage message printed out for usage errors when running under the SMF.
3826  */
3827 static void
3828 smf_usage(const char *arg0)
3829 {
3830 	error_msg("Usage: %s [alt_conf_file] %s|%s|%s", arg0, START_METHOD_ARG,
3831 	    STOP_METHOD_ARG, REFRESH_METHOD_ARG);
3832 }
3833 
3834 /*
3835  * Returns B_TRUE if we're being run from within the SMF, else B_FALSE.
3836  */
3837 static boolean_t
3838 run_through_smf(void)
3839 {
3840 	char *fmri;
3841 
3842 	/*
3843 	 * check if the instance fmri environment variable has been set by
3844 	 * our restarter.
3845 	 */
3846 	return (((fmri = getenv("SMF_FMRI")) != NULL) &&
3847 	    (strcmp(fmri, INETD_INSTANCE_FMRI) == 0));
3848 }
3849 
3850 int
3851 main(int argc, char *argv[])
3852 {
3853 	char		*method;
3854 	int		ret;
3855 
3856 #if	!defined(TEXT_DOMAIN)
3857 #define	TEXT_DOMAIN "SYS_TEST"
3858 #endif
3859 	(void) textdomain(TEXT_DOMAIN);
3860 	(void) setlocale(LC_ALL, "");
3861 
3862 	if (!run_through_smf()) {
3863 		legacy_usage();
3864 		return (SMF_EXIT_ERR_NOSMF);
3865 	}
3866 
3867 	msg_init();	/* setup logging */
3868 
3869 	(void) enable_extended_FILE_stdio(-1, -1);
3870 
3871 	/* inetd invocation syntax is inetd [alt_conf_file] method_name */
3872 
3873 	switch (argc) {
3874 	case 2:
3875 		method = argv[1];
3876 		break;
3877 	case 3:
3878 		conf_file = argv[1];
3879 		method = argv[2];
3880 		break;
3881 	default:
3882 		smf_usage(argv[0]);
3883 		return (SMF_EXIT_ERR_CONFIG);
3884 
3885 	}
3886 
3887 	if (strcmp(method, START_METHOD_ARG) == 0) {
3888 		ret = start_method();
3889 	} else if (strcmp(method, STOP_METHOD_ARG) == 0) {
3890 		ret = stop_method();
3891 	} else if (strcmp(method, REFRESH_METHOD_ARG) == 0) {
3892 		ret = refresh_method();
3893 	} else {
3894 		smf_usage(argv[0]);
3895 		return (SMF_EXIT_ERR_CONFIG);
3896 	}
3897 
3898 	return (ret);
3899 }
3900