$NetBSD: rc.subr.8,v 1.12 2004/01/06 00:52:24 lukem Exp $

Copyright (c) 2002-2004 The NetBSD Foundation, Inc.
All rights reserved.

This code is derived from software contributed to The NetBSD Foundation
by Luke Mewburn.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

.Dd June 2, 2024 .Dt RC.SUBR 8 .Os .Sh NAME .Nm rc.subr .Nd functions used by system shell scripts .Sh SYNOPSIS l -item -compact t c . Pa /etc/rc.subr

p t c backup_file Ar action Ar file Ar current Ar backup t c checkyesno Ar var t c check_pidfile Ar pidfile Ar procname Op Ar interpreter t c check_process Ar procname Op Ar interpreter t c DebugOn Ar tag ... t c DebugOff Ar tag ... t c debug Ar message t c dot Ar file ... t c err Ar exitval Ar message t c force_depend Ar name t c info Ar message t c is_verified Ar file t c load_kld Oo Fl e Ar regex Oc Oo Fl m Ar module Oc Ar file t c load_rc_config Oo Ar flag Oc Op Ar service t c load_rc_config_var Ar name Ar var t c mount_critical_filesystems Ar type t c rc_log Ar message t t rc_trace Ar level Ar message t c rc_usage Ar command ... t c reverse_list Ar item ... t c run_rc_command Ar argument t c run_rc_script Ar file Ar argument t c run_rc_scripts Oo options Oc Ar file ... t c safe_dot Ar file ... t c sdot Ar file ... t c startmsg Oo Fl n Oc Ar message t c vdot Ar file ... t c wait_for_pids Op Ar pid ... t c warn Ar message .El .Sh DESCRIPTION The .Nm script contains commonly used shell script functions and variable definitions which are used by various scripts such as .Xr rc 8 . Scripts required by ports in

a /usr/local/etc/rc.d will also eventually be rewritten to make use of it.

p The .Nm functions were mostly imported from .Nx .

p They are accessed by sourcing

a /etc/rc.subr into the current shell.

p The following shell functions are available: l -tag -width 4n t Ic backup_file Ar action file current backup Make a backup copy of .Ar file into .Ar current . Save the previous version of .Ar current as .Ar backup .

p The .Ar action argument may be one of the following: l -tag -width ".Cm remove" t Cm add .Ar file is now being backed up by or possibly re-entered into this backup mechanism. .Ar current is created. t Cm update .Ar file has changed and needs to be backed up. If .Ar current exists, it is copied to .Ar backup and then .Ar file is copied to .Ar current . t Cm remove .Ar file is no longer being tracked by this backup mechanism. .Ar current is moved to .Ar backup . .El t Ic checkyesno Ar var Return 0 if .Ar var is defined to .Dq Li YES , .Dq Li TRUE , .Dq Li ON , or .Ql 1 . Return 1 if .Ar var is defined to .Dq Li NO , .Dq Li FALSE , .Dq Li OFF , or .Ql 0 . Otherwise, warn that .Ar var is not set correctly. The values are case insensitive. .Em Note : .Ar var should be a variable name, not its value; c checkyesno will expand the variable by itself. t Ic check_pidfile Ar pidfile procname Op Ar interpreter Parses the first word of the first line of .Ar pidfile for a PID, and ensures that the process with that PID is running and its first argument matches .Ar procname . Prints the matching PID if successful, otherwise nothing. If .Ar interpreter is provided, parse the first line of .Ar procname , ensure that the line is of the form:

p .Dl "#! interpreter [...]"

p and use .Ar interpreter with its optional arguments and .Ar procname appended as the process string to search for. t Ic check_process Ar procname Op Ar interpreter Prints the PIDs of any processes that are running with a first argument that matches .Ar procname . .Ar interpreter is handled as per c check_pidfile . t Ic DebugOn Ar tag ... Enable tracing if not already enabled, and any .Ar tag is found in .Va DEBUG_SH (a comma separated list of tags).

p Record the .Ar tag that caused it to be enabled in .Va DEBUG_ON , set .Va DEBUG_DO empty and .Va DEBUG_SKIP to .Ql : .

p See .Xr debug.sh 8 for more details. t Ic DebugOff Ar tag ... Disable tracing if enabled and any .Ar tag matches .Va DEBUG_ON , which means it was the reason tracing was enabled.

p Set .Va DEBUG_DO to .Ql : , and .Va DEBUG_ON , .Va DEBUG_SKIP empty. t Ic debug Ar message Display a debugging message to .Va stderr , log it to the system log using .Xr logger 1 , and return to the caller. The error message consists of the script name (from .Va $0 ) , followed by .Dq Li ": DEBUG: " , and then .Ar message . This function is intended to be used by developers as an aid to debugging scripts. It can be turned on or off by the .Xr rc.conf 5 variable .Va rc_debug . t Ic dot Ar file ... For reading in unverified files.

p Ensure shell .Li verify option is off. This option is only meaningful when .Xr mac_veriexec 4 is active.

p Read each .Ar file if it exists.

p Restore previous state of the .Li verify option. t Ic err Ar exitval message Display an error message to .Va stderr , log it to the system log using .Xr logger 1 , and c exit with an exit value of .Ar exitval . The error message consists of the script name (from .Va $0 ) , followed by .Dq Li ": ERROR: " , and then .Ar message . t Ic force_depend Ar name Output an advisory message and force the .Ar name service to start. The .Ar name argument is the .Xr basename 1 component of the path to the script located at

a /etc/rc.d (scripts stored in other locations such as

a /usr/local/etc/rc.d cannot be controlled with c force_depend currently). If the script fails for any reason it will output a warning and return with a return value of 1. If it was successful it will return 0. t Ic is_verified Ar file If .Xr veriexec 8 does not exist, or .Xr mac_veriexec 4 is not active, just return success. Otherwise use .Xr veriexec 8 to check if .Ar file is verified. If not verified the return code will be 80 (EAUTH). t Ic info Ar message Display an informational message to .Va stdout , and log it to the system log using .Xr logger 1 . The message consists of the script name (from .Va $0 ) , followed by .Dq Li ": INFO: " , and then .Ar message . The display of this informational output can be turned on or off by the .Xr rc.conf 5 variable .Va rc_info . t Ic load_kld Oo Fl e Ar regex Oc Oo Fl m Ar module Oc Ar file Load .Ar file as a kernel module unless it is already loaded. For the purpose of checking the module status, either the exact module name can be specified using .Fl m , or an .Xr egrep 1 regular expression matching the module name can be supplied via .Fl e . By default, the module is assumed to have the same name as .Ar file , which is not always the case. t Ic load_rc_config Oo Ar flag Oc Op Ar service Source in the configuration file(s) for .Ar service . If no .Ar service is specified, only the global configuration file(s) will be loaded. First,

a /etc/rc.conf is sourced if it has not yet been read in. Then,

a /etc/rc.conf.d/ Ns Ar service is sourced if it is an existing file. The latter may also contain other variable assignments to override c run_rc_command arguments defined by the calling script, to provide an easy mechanism for an administrator to override the behaviour of a given .Xr rc.d 8 script without requiring the editing of that script.

p The function named by .Va load_rc_config_reader (default is c dot ) is used to read configuration unless .Ar flag is: l -tag -width Ds t Fl s use c sdot to read configuration, because we want verified configuration or to use c safe_dot to read an unverified configuration. t Fl v use c vdot to read in configuration only if it is verified. .El

p c DebugOn will be called with tags derived from .Ar name to enable tracing if any appear in .Va DEBUG_SH . t Ic load_rc_config_var Ar name Ar var Read the .Xr rc.conf 5 variable .Ar var for .Ar name and set in the current shell, using c load_rc_config in a sub-shell to prevent unwanted side effects from other variable assignments. t Ic mount_critical_filesystems Ar type Go through a list of critical file systems, as found in the .Xr rc.conf 5 variable .Va critical_filesystems_ Ns Ar type , mounting each one that is not currently mounted. t Ic rc_log Ar message Output .Ar message with a timestamp, which is both human readable and easily parsed for post processing, using: d -literal -offset indent date "+@ %s [%Y-%m-%d %H:%M:%S %Z] $*" .Ed t Ic rc_trace Ar level Ar message If the file

a /etc/rc.conf.d/rc_trace exists and is not empty attempt to set .Va RC_LEVEL based on its content. If the file is empty or does not contain a value for .Va RC_LEVEL , set it to .Li 0 .

p If .Ar level is greater than or equal to .Va RC_LEVEL pass .Ar message to c rc_log . t Ic rc_usage Ar command ... Print a usage message for .Va $0 , with .Ar commands being the list of valid arguments prefixed by .Sm off .Dq Bq Li fast | force | one | quiet . .Sm on t Ic reverse_list Ar item ... Print the list of .Ar items in reverse order. t Ic run_rc_command Ar argument Run the .Ar argument method for the current .Xr rc.d 8 script, based on the settings of various shell variables. c run_rc_command is extremely flexible, and allows fully functional .Xr rc.d 8 scripts to be implemented in a small amount of shell code.

p .Ar argument is searched for in the list of supported commands, which may be one of: l -tag -width ".Cm restart" -offset indent t Cm start Start the service. This should check that the service is to be started as specified by .Xr rc.conf 5 . Also checks if the service is already running and refuses to start if it is. This latter check is not performed by standard .Fx scripts if the system is starting directly to multi-user mode, to speed up the boot process. t Cm stop If the service is to be started as specified by .Xr rc.conf 5 , stop the service. This should check that the service is running and complain if it is not. t Cm restart Perform a .Cm stop then a .Cm start . Defaults to displaying the process ID of the program (if running). t Cm enabled Return 0 if the service is enabled and 1 if it is not. This command does not print anything. t Cm rcvar Display which .Xr rc.conf 5 variables are used to control the startup of the service (if any). .El

p If .Va pidfile or .Va procname is set, also support: l -tag -width ".Cm restart" -offset indent t Cm poll Wait for the command to exit. t Cm status Show the status of the process. .El

p Other supported commands are listed in the optional variable .Va extra_commands .

p .Ar argument may have one of the following prefixes which alters its operation: l -tag -width ".Li force" -offset indent t Li fast Skip the check for an existing running process, and sets .Va rc_fast Ns = Ns Li YES . t Li force Skip the checks for .Va rcvar being set to .Dq Li YES , and sets .Va rc_force Ns = Ns Li YES . This ignores .Ar argument Ns Va _precmd returning non-zero, and ignores any of the .Va required_* tests failing, and always returns a zero exit status. t Li one Skip the checks for .Va rcvar being set to .Dq Li YES , but performs all the other prerequisite tests. t Li quiet Inhibits some verbose diagnostics. Currently, this includes messages .Qq Starting ${name} (as checked by c check_startmsgs inside .Nm ) and errors about usage of services that are not enabled in .Xr rc.conf 5 . This prefix also sets .Va rc_quiet Ns = Ns Li YES . .Em Note : .Va rc_quiet is not intended to completely mask all debug and warning messages, but only certain small classes of them. .El

p c run_rc_command uses the following shell variables to control its behaviour. Unless otherwise stated, these are optional. l -tag -width ".Va procname" -offset indent t Va name The name of this script. This is not optional. t Va rcvar The value of .Va rcvar is checked with c checkyesno to determine if this method should be run. t Va command Full path to the command. Not required if .Ar argument Ns Va _cmd is defined for each supported keyword. Can be overridden by .Va ${name}_program . t Va command_args Optional arguments and/or shell directives for .Va command . t Va command_interpreter .Va command is started with:

p .Dl "#! command_interpreter [...]"

p which results in its .Xr ps 1 command being:

p .Dl "command_interpreter [...] command"

p so use that string to find the PID(s) of the running command rather than .Va command . t Va extra_commands Extra commands/keywords/arguments supported. t Va pidfile Path to PID file. Used to determine the PID(s) of the running command. If .Va pidfile is set, use:

p .Dl "check_pidfile $pidfile $procname"

p to find the PID. Otherwise, if .Va command is set, use:

p .Dl "check_process $procname"

p to find the PID. t Va procname Process name to check for. Defaults to the value of .Va command . t Va required_dirs Check for the existence of the listed directories before running the .Cm start method. The list is checked before running .Va start_precmd . t Va required_files Check for the readability of the listed files before running the .Cm start method. The list is checked before running .Va start_precmd . t Va required_modules Ensure that the listed kernel modules are loaded before running the .Cm start method. The list is checked after running .Va start_precmd . This is done after invoking the commands from .Va start_precmd so that the missing modules are not loaded in vain if the preliminary commands indicate a error condition. A word in the list can have an optional .Dq Li : Ns Ar modname or .Dq Li ~ Ns Ar pattern suffix. The .Ar modname or .Ar pattern parameter is passed to c load_kld through a .Fl m or .Fl e option, respectively. See the description of c load_kld in this document for details. t Va required_vars Perform c checkyesno on each of the list variables before running the .Cm start method. The list is checked after running .Va start_precmd . t Va ${name}_chdir Directory to c cd to before running .Va command , if .Va ${name}_chroot is not provided. t Va ${name}_chroot Directory to .Xr chroot 8 to before running .Va command . Only supported after

a /usr is mounted. t Va ${name}_env A list of environment variables to run .Va command with. Those variables will be passed as arguments to the .Xr env 1 utility unless .Ar argument Ns Va _cmd is defined. In that case the contents of .Va ${name}_env will be exported via the .Xr export 1 builtin of .Xr sh 1 , which puts some limitations on the names of variables (e.g., a variable name may not start with a digit). t Va ${name}_env_file A file to source for environmental variables to run .Va command with. .Em Note : all the variables which are being assigned in this file are going to be exported into the environment of .Va command . t Va ${name}_fib FIB

a Routing Table number to run .Va command with. See .Xr setfib 1 for more details. t Va ${name}_flags Arguments to call .Va command with. This is usually set in .Xr rc.conf 5 , and not in the .Xr rc.d 8 script. The environment variable .Sq Ev flags can be used to override this. t Va ${name}_nice .Xr nice 1 level to run .Va command as. Only supported after

a /usr is mounted. t Va ${name}_limits Resource limits to apply to .Va command . This will be passed as arguments to the .Xr limits 1 utility. By default, the resource limits are based on the login class defined in .Va ${name}_login_class . t Va ${name}_login_class Login class to use with .Va ${name}_limits . Defaults to .Dq Li daemon . t Va ${name}_offcmd Shell commands to run if a service is not enabled. t Va ${name}_oomprotect .Xr protect 1 .Va command from being killed when swap space is exhausted. If .Dq Li YES is used, no child processes are protected. If .Dq Li ALL , protect all child processes. t Va ${name}_program Full path to the command. Overrides .Va command if both are set, but has no effect if .Va command is unset. As a rule, .Va command should be set in the script while .Va ${name}_program should be set in .Xr rc.conf 5 . t Va ${name}_user User to run .Va command as, using .Xr chroot 8 if .Va ${name}_chroot is set, otherwise uses .Xr su 1 . Only supported after

a /usr is mounted. t Va ${name}_group Group to run the chrooted .Va command as. t Va ${name}_groups Comma separated list of supplementary groups to run the chrooted .Va command with. t Va ${name}_prepend Commands to be prepended to .Va command . This is a generic version of .Va ${name}_env , .Va ${name}_fib , or .Va ${name}_nice . t Va ${name}_setup Optional command to be run during .Cm start , .Cm restart , and .Cm reload prior to the respective .Ar argument Ns Va _precmd . If the command fails for any reason it will output a warning, but execution will continue. t Ar argument Ns Va _cmd Shell commands which override the default method for .Ar argument . t Ar argument Ns Va _precmd Shell commands to run just before running .Ar argument Ns Va _cmd or the default method for .Ar argument . If this returns a non-zero exit code, the main method is not performed. If the default method is being executed, this check is performed after the .Va required_* checks and process (non-)existence checks. t Ar argument Ns Va _postcmd Shell commands to run if running .Ar argument Ns Va _cmd or the default method for .Ar argument returned a zero exit code. t Va sig_stop Signal to send the processes to stop in the default .Cm stop method. Defaults to .Dv SIGTERM . t Va sig_reload Signal to send the processes to reload in the default .Cm reload method. Defaults to .Dv SIGHUP . .El

p For a given method .Ar argument , if .Ar argument Ns Va _cmd is not defined, then a default method is provided by c run_rc_command : l -tag -width ".Sy Argument" -offset indent t Sy Argument .Sy Default method t Cm start If .Va command is not running and c checkyesno Va rcvar succeeds, start .Va command . t Cm stop Determine the PIDs of .Va command with c check_pidfile or c check_process (as appropriate), c kill Va sig_stop those PIDs, and run c wait_for_pids on those PIDs. t Cm reload Similar to .Cm stop , except that it uses .Va sig_reload instead, and does not run c wait_for_pids . Another difference from .Cm stop is that .Cm reload is not provided by default. It can be enabled via .Va extra_commands if appropriate:

p .Dl "extra_commands=reload" t Cm restart Runs the .Cm stop method, then the .Cm start method. t Cm status Show the PID of .Va command , or some other script specific status operation. t Cm poll Wait for .Va command to exit. t Cm rcvar Display which .Xr rc.conf 5 variable is used (if any). This method always works, even if the appropriate .Xr rc.conf 5 variable is set to .Dq Li NO . .El

p The following variables are available to the methods (such as .Ar argument Ns Va _cmd ) as well as after c run_rc_command has completed: l -tag -width ".Va rc_service" -offset indent t Va rc_arg Argument provided to c run_rc_command , after fast and force processing has been performed. t Va rc_flags Flags to start the default command with. Defaults to .Va ${name}_flags , unless overridden by the environment variable .Sq Ev flags . This variable may be changed by the .Ar argument Ns Va _precmd method. t Va rc_service Path to the service script being executed, in case it needs to re-invoke itself. t Va rc_pid PID of .Va command (if appropriate). t Va rc_fast Not empty if .Dq Li fast prefix was used. t Va rc_force Not empty if .Dq Li force prefix was used. .El t Ic run_rc_script Ar file argument Start the script .Ar file with an argument of .Ar argument , and handle the return value from the script.

p Various shell variables are unset before .Ar file is started: d -ragged -offset indent .Va name , .Va command , .Va command_args , .Va command_interpreter , .Va extra_commands , .Va pidfile , .Va rcvar , .Va required_dirs , .Va required_files , .Va required_vars , .Ar argument Ns Va _cmd , .Ar argument Ns Va _precmd . .Ar argument Ns Va _postcmd . .Ed

p Call c rc_trace to indicate that .Ar file is to be run.

p However, if c is_verified Ar file fails, just return.

p c DebugOn will be called with tags derrived from .Va name and .Va rc_arg to enable tracing if any of those tags appear in .Va DEBUG_SH .

p The startup behaviour of .Ar file depends upon the following checks: l -enum t If .Ar file ends in

a .sh , it is sourced into the current shell. t If .Ar file appears to be a backup or scratch file (e.g., with a suffix of

a ~ , # , .OLD , or

a .orig ) , ignore it. t If .Ar file is not executable, ignore it. t If the .Xr rc.conf 5 variable .Va rc_fast_and_loose is empty, source .Ar file in a sub shell, otherwise source .Ar file into the current shell. .El t Ic run_rc_scripts Oo options Oc file ... Call c run_rc_script for each .Ar file , unless it is already recorded as having been run.

p The .Ar options are: l -tag -width "--break break" t Ic --arg Ar arg Pass .Ar arg to c run_rc_script , default is .Ar _boot set by .Xr rc 8 . t Ic --break Ar break Stop processing if any .Ar file matches any .Ar break .El t Ic safe_dot Ar file ... Used by c sdot when .Xr mac_veriexec 4 is active and .Ar file is not verified.

p This function limits the input from .Ar file to simple variable assignments with any non-alphanumeric characters replaced with .Ql _ . t Ic sdot Ar file ... For reading in configuration files. Skip files that do not exist or are empty. Try using c vdot and if that fails (the file is unverified) fall back to using c safe_dot . t Ic startmsg Oo Fl n Oc Ar message Display a start message to .Va stdout . It should be used instead of .Xr echo 1 . The display of this output can be turned off if the .Xr rc.conf 5 variable .Va rc_startmsgs is set to .Dq Li NO . t Ic stop_boot Op Ar always Prevent booting to multiuser mode. If the .Va autoboot variable is set to .Ql yes (see .Xr rc 8 to learn more about .Va autoboot ) , or c checkyesno Ar always indicates a truth value, then a .Dv SIGTERM signal is sent to the parent process, which is assumed to be .Xr rc 8 . Otherwise, the shell exits with a non-zero status. t Ic vdot Ar file ... For reading in only verified files.

p Ensure shell .Li verify option is on. This option is only meaningful when .Xr mac_veriexec 4 is active, otherwise this function is effectively the same as c dot .

p Read in each .Ar file if it exists and c is_verfied Ar file is successful, otherwise set return code to 80 (EAUTH).

p Restore previous state of the .Li verify option. t Ic wait_for_pids Op Ar pid ... Wait until all of the provided .Ar pids do not exist any more, printing the list of outstanding .Ar pids every two seconds. t Ic warn Ar message Display a warning message to .Va stderr and log it to the system log using .Xr logger 1 . The warning message consists of the script name (from .Va $0 ) , followed by .Dq Li ": WARNING: " , and then .Ar message . .El .Sh FILES l -tag -width ".Pa /etc/rc.subr" -compact t Pa /etc/rc.subr The .Nm file resides in

a /etc . .El .Sh SEE ALSO .Xr debug.sh 8 , .Xr rc.conf 5 , .Xr rc 8 .Sh HISTORY The .Nm script appeared in .Nx 1.3 . The .Xr rc.d 8 support functions appeared in .Nx 1.5 . The .Nm script first appeared in .Fx 5.0 .