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