rc.subr revision 1.108
1# $NetBSD: rc.subr,v 1.108 2022/02/03 20:52:44 alnsn Exp $ 2# 3# Copyright (c) 1997-2011 The NetBSD Foundation, Inc. 4# All rights reserved. 5# 6# This code is derived from software contributed to The NetBSD Foundation 7# by Luke Mewburn. 8# 9# Redistribution and use in source and binary forms, with or without 10# modification, are permitted provided that the following conditions 11# are met: 12# 1. Redistributions of source code must retain the above copyright 13# notice, this list of conditions and the following disclaimer. 14# 2. Redistributions in binary form must reproduce the above copyright 15# notice, this list of conditions and the following disclaimer in the 16# documentation and/or other materials provided with the distribution. 17# 18# THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 19# ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 20# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 21# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 22# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 28# POSSIBILITY OF SUCH DAMAGE. 29# 30# rc.subr 31# functions used by various rc scripts 32# 33 34: ${rcvar_manpage:='rc.conf(5)'} 35: ${RC_PID:=$$} ; export RC_PID 36nl=' 37' # a literal newline 38 39# RC variables to clear on start. 40_env_clear_rc_vars=" 41RC_PID= 42_rc_pid= 43_rc_original_stdout_fd= 44_rc_original_stderr_fd= 45_rc_postprocessor_fd= 46_rc_kill_ntries= 47" 48 49export PATH=/sbin:/bin:/usr/sbin:/usr/bin 50# 51# functions 52# --------- 53 54# 55# checkyesno var 56# Test $1 variable. 57# Return 0 if it's "yes" (et al), 1 if it's "no" (et al), 2 otherwise. 58# 59checkyesnox() 60{ 61 eval _value=\$${1} 62 case $_value in 63 64 # "yes", "true", "on", or "1" 65 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1) 66 return 0 67 ;; 68 69 # "no", "false", "off", or "0" 70 [Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0) 71 return 1 72 ;; 73 *) 74 return 2 75 ;; 76 esac 77} 78 79# 80# checkyesno var 81# Test $1 variable, and warn if not set to YES or NO. 82# Return 0 if it's "yes" (et al), nonzero otherwise. 83# 84checkyesno() 85{ 86 local var 87 88 checkyesnox $1 89 var=$? 90 case "${var}" in 91 ( 0 | 1 ) return $var;; 92 esac 93 warn "\$${1} is not set properly - see ${rcvar_manpage}." 94 return 1 95} 96 97# 98# yesno_to_truefalse var 99# Convert the value of a variable from any of the values 100# understood by checkyesno() to "true" or "false". 101# 102yesno_to_truefalse() 103{ 104 local var=$1 105 if checkyesno $var; then 106 eval $var=true 107 return 0 108 else 109 eval $var=false 110 return 1 111 fi 112} 113 114# 115# reverse_list list 116# print the list in reverse order 117# 118reverse_list() 119{ 120 _revlist= 121 for _revfile; do 122 _revlist="$_revfile $_revlist" 123 done 124 echo $_revlist 125} 126 127# 128# If booting directly to multiuser, send SIGTERM to 129# the parent (/etc/rc) to abort the boot. 130# Otherwise just exit. 131# 132stop_boot() 133{ 134 if [ "$autoboot" = yes ]; then 135 echo "ERROR: ABORTING BOOT (sending SIGTERM to parent)!" 136 kill -TERM ${RC_PID} 137 fi 138 exit 1 139} 140 141# 142# mount_critical_filesystems type 143# Go through the list of critical file systems as provided in 144# the rc.conf(5) variable $critical_filesystems_${type}, checking 145# each one to see if it is mounted, and if it is not, mounting it. 146# It's not an error if file systems prefixed with "OPTIONAL:" 147# are not mentioned in /etc/fstab. 148# 149mount_critical_filesystems() 150{ 151 eval _fslist=\$critical_filesystems_${1} 152 _mountcrit_es=0 153 for _fs in $_fslist; do 154 _optional=false 155 case "$_fs" in 156 OPTIONAL:*) 157 _optional=true 158 _fs="${_fs#*:}" 159 ;; 160 esac 161 _ismounted=false 162 # look for a line like "${fs} on * type *" 163 # or "* on ${fs} type *" in the output from mount. 164 case "${nl}$( mount )${nl}" in 165 *" on ${_fs} type "*) 166 _ismounted=true 167 ;; 168 *"${nl}${_fs} on "*) 169 _ismounted=true 170 ;; 171 esac 172 if $_ismounted; then 173 print_rc_metadata \ 174 "note:File system ${_fs} was already mounted" 175 else 176 _mount_output=$( mount $_fs 2>&1 ) 177 _mount_es=$? 178 case "$_mount_output" in 179 *"${nl}"*) 180 # multiple lines can't be good, 181 # not even if $_optional is true 182 ;; 183 *[uU]'nknown special file or file system'*) 184 if $_optional; then 185 # ignore this error 186 print_rc_metadata \ 187 "note:Optional file system ${_fs} is not present" 188 _mount_es=0 189 _mount_output="" 190 fi 191 ;; 192 esac 193 if [ -n "$_mount_output" ]; then 194 printf >&2 "%s\n" "$_mount_output" 195 fi 196 if [ "$_mount_es" != 0 ]; then 197 _mountcrit_es="$_mount_es" 198 fi 199 fi 200 done 201 return $_mountcrit_es 202} 203 204# 205# mount_critical_filesystems_zfs 206# Go through the list of critical ZFS mountpoints as provided in 207# the rc.conf(5) variable $critical_filesystems_zfs, checking 208# each one to see if it is mounted, and if it is not, mounting it. 209# It's not an error if file systems prefixed with "OPTIONAL:" 210# aren't zfs mountpoints. 211mount_critical_filesystems_zfs() 212{ 213 eval _fslist=\$critical_filesystems_zfs 214 _tab=" " 215 _mountcrit_es=0 216 for _fs in $_fslist; do 217 _optional=false 218 case "$_fs" in 219 OPTIONAL:*) 220 _optional=true 221 _fs="${_fs#*:}" 222 ;; 223 esac 224 225 _dataset=` 226 zfs list -H -o mountpoint,name | 227 while read _line ; do 228 _dataset='' 229 case "$_line" in 230 "${_fs}${_tab}"*) 231 _dataset="${_line#*${_tab}}" 232 ;; 233 esac 234 if [ -n "$_dataset" ]; then 235 case "$( zfs get -H -o value canmount $_dataset )" in 236 on) 237 echo -n "$_dataset" 238 break ;; 239 *) # noauto|off - dataset isn't supposed to be mounted 240 ;; 241 esac 242 fi 243 done` 244 245 if [ -z "$_dataset" ]; then 246 if $_optional; then 247 # ignore this error 248 print_rc_metadata \ 249 "note:Optional file system $_fs is not present" 250 else 251 printf >&2 "%s\n" "No suitable ZFS dataset found for mountpoint $_fs" 252 _mountcrit_es=1 253 fi 254 else 255 _mount_es= 256 case "$( zfs get -H -o value mounted $_dataset )" in 257 yes) 258 _mount_es=1 259 print_rc_metadata \ 260 "note:File system $_fs was already mounted" 261 ;; 262 esac 263 264 if [ -z "$_mount_es" ]; then 265 zfs mount "$_dataset" >/dev/null 266 _mount_es=$? 267 fi 268 269 if [ -n "$_mount_es" ]; then 270 _mountcrit_es="$_mount_es" 271 fi 272 fi 273 done 274 return $_mountcrit_es 275} 276 277# 278# check_pidfile pidfile procname [interpreter] 279# Parses the first line of pidfile for a PID, and ensures 280# that the process is running and matches procname. 281# Prints the matching PID upon success, nothing otherwise. 282# interpreter is optional; see _find_processes() for details. 283# 284check_pidfile() 285{ 286 _pidfile=$1 287 _procname=$2 288 _interpreter=$3 289 if [ -z "$_pidfile" ] || [ -z "$_procname" ]; then 290 err 3 'USAGE: check_pidfile pidfile procname [interpreter]' 291 fi 292 if [ ! -f $_pidfile ]; then 293 return 294 fi 295 read _pid _junk < $_pidfile 296 if [ -z "$_pid" ]; then 297 return 298 fi 299 _find_processes $_procname ${_interpreter:-.} '-p '"$_pid" 300} 301 302# 303# check_process procname [interpreter] 304# Ensures that a process (or processes) named procname is running. 305# Prints a list of matching PIDs. 306# interpreter is optional; see _find_processes() for details. 307# 308check_process() 309{ 310 _procname=$1 311 _interpreter=$2 312 if [ -z "$_procname" ]; then 313 err 3 'USAGE: check_process procname [interpreter]' 314 fi 315 _find_processes $_procname ${_interpreter:-.} '-A' 316} 317 318# 319# _find_processes procname interpreter psargs 320# Search for procname in the output of ps generated by psargs. 321# Prints the PIDs of any matching processes, space separated. 322# 323# If interpreter == ".", check the following variations of procname 324# against the first word of each command: 325# procname 326# `basename procname` 327# `basename procname` + ":" 328# "(" + `basename procname` + ")" 329# 330# If interpreter != ".", read the first line of procname, remove the 331# leading #!, normalise whitespace, append procname, and attempt to 332# match that against each command, either as is, or with extra words 333# at the end. As an alternative, to deal with interpreted daemons 334# using perl, the basename of the interpreter plus a colon is also 335# tried as the prefix to procname. 336# 337_find_processes() 338{ 339 if [ $# -ne 3 ]; then 340 err 3 'USAGE: _find_processes procname interpreter psargs' 341 fi 342 _procname=$1 343 _interpreter=$2 344 _psargs=$3 345 346 _pref= 347 _procnamebn=${_procname##*/} 348 if [ $_interpreter != "." ]; then # an interpreted script 349 read _interp < ${_chroot:-}/$_procname # read interpreter name 350 _interp=${_interp#\#!} # strip #! 351 set -- $_interp 352 if [ $1 = "/usr/bin/env" ]; then 353 shift 354 set -- $(type $1) 355 shift $(($# - 1)) 356 _interp="${1##*/} $_procname" 357 else 358 _interp="$* $_procname" 359 fi 360 if [ $_interpreter != $1 ]; then 361 warn "\$command_interpreter $_interpreter != $1" 362 fi 363 _interpbn=${1##*/} 364 _fp_args='_argv' 365 _fp_match='case "$_argv" in 366 ${_interp}|"${_interp} "*|"${_interpbn}: "*${_procnamebn}*)' 367 else # a normal daemon 368 _fp_args='_arg0 _argv' 369 _fp_match='case "$_arg0" in 370 $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})")' 371 fi 372 373 _proccheck=' 374 ps -o "pid,args" '"$_psargs"' 2>&1 | 375 while read _npid '"$_fp_args"'; do 376 case "$_npid" in 377 ps:|PID) 378 continue ;; 379 esac ; '"$_fp_match"' 380 echo -n "$_pref$_npid" ; 381 _pref=" " 382 ;; 383 esac 384 done' 385 386#echo 1>&2 "proccheck is :$_proccheck:" 387 eval $_proccheck 388} 389 390# 391# kill_pids signal pid [pid ...] 392# kills the given pids with signal. 393# returns the list of pids killed successfully. 394# 395kill_pids() 396{ 397 local signal=$1 398 shift 399 local list="$*" 400 local j= 401 local nlist= 402 for j in $list; do 403 if kill -$signal $j 2>/dev/null; then 404 nlist="${nlist}${nlist:+ }$j" 405 fi 406 done 407 echo $nlist 408} 409 410# 411# wait_for_pids pid [pid ...] 412# spins until none of the pids exist 413# if _rc_kill_ntries is set and exceeded, it SIGKILLS the remaining 414# pids 415# 416wait_for_pids() 417{ 418 local ntries=0 419 local prefix= 420 local nlist= 421 local list="$*" 422 423 if [ -z "$list" ]; then 424 return 425 fi 426 427 while true; do 428 nlist=$(kill_pids 0 $list) 429 if [ -z "$nlist" ]; then 430 break 431 fi 432 if [ "$list" != "$nlist" ]; then 433 list=$nlist 434 echo -n ${prefix:-"Waiting for PIDS: "}$list 435 prefix=", " 436 fi 437 # We want this to be a tight loop for a fast exit 438 sleep 0.05 439 ntries=$((ntries + 1)) 440 if [ -n "${_rc_kill_ntries}" ]; then 441 if [ ${ntries} -gt ${_rc_kill_ntries} ]; then 442 kill_pids 9 $list > /dev/null 443 fi 444 fi 445 done 446 if [ -n "$prefix" ]; then 447 echo "." 448 fi 449} 450 451# 452# run_rc_command argument [parameters] 453# Search for argument in the list of supported commands, which is: 454# "start stop restart rcvar status poll ${extra_commands}" 455# If there's a match, run ${argument}_cmd or the default method 456# (see below), and pass the optional list of parameters to it. 457# 458# If argument has a given prefix, then change the operation as follows: 459# Prefix Operation 460# ------ --------- 461# fast Skip the pid check, and set rc_fast=yes 462# force Set ${rcvar} to YES, and set rc_force=yes 463# one Set ${rcvar} to YES 464# 465# The following globals are used: 466# 467# Name Needed Purpose 468# ---- ------ ------- 469# name y Name of script. 470# 471# command n Full path to command. 472# Not needed if ${rc_arg}_cmd is set for 473# each keyword. 474# 475# command_args n Optional args/shell directives for command. 476# 477# command_interpreter n If not empty, command is interpreted, so 478# call check_{pidfile,process}() appropriately. 479# 480# extra_commands n List of extra commands supported. 481# 482# pidfile n If set, use check_pidfile $pidfile $command, 483# otherwise use check_process $command. 484# In either case, only check if $command is set. 485# 486# procname n Process name to check for instead of $command. 487# 488# rcvar n This is checked with checkyesno to determine 489# if the action should be run. 490# 491# ${name}_chroot n Directory to chroot to before running ${command} 492# Requires /usr to be mounted. 493# 494# ${name}_chdir n Directory to cd to before running ${command} 495# (if not using ${name}_chroot). 496# 497# ${name}_flags n Arguments to call ${command} with. 498# NOTE: $flags from the parent environment 499# can be used to override this. 500# 501# ${name}_env n Additional environment variable settings 502# for running ${command} 503# 504# ${name}_nice n Nice level to run ${command} at. 505# 506# ${name}_user n User to run ${command} as, using su(1) if not 507# using ${name}_chroot. 508# Requires /usr to be mounted. 509# 510# ${name}_group n Group to run chrooted ${command} as. 511# Requires /usr to be mounted. 512# 513# ${name}_groups n Comma separated list of supplementary groups 514# to run the chrooted ${command} with. 515# Requires /usr to be mounted. 516# 517# ${rc_arg}_cmd n If set, use this as the method when invoked; 518# Otherwise, use default command (see below) 519# 520# ${rc_arg}_precmd n If set, run just before performing the 521# ${rc_arg}_cmd method in the default 522# operation (i.e, after checking for required 523# bits and process (non)existence). 524# If this completes with a non-zero exit code, 525# don't run ${rc_arg}_cmd. 526# 527# ${rc_arg}_postcmd n If set, run just after performing the 528# ${rc_arg}_cmd method, if that method 529# returned a zero exit code. 530# 531# required_dirs n If set, check for the existence of the given 532# directories before running the default 533# (re)start command. 534# 535# required_files n If set, check for the readability of the given 536# files before running the default (re)start 537# command. 538# 539# required_vars n If set, perform checkyesno on each of the 540# listed variables before running the default 541# (re)start command. 542# 543# Default behaviour for a given argument, if no override method is 544# provided: 545# 546# Argument Default behaviour 547# -------- ----------------- 548# start if !running && checkyesno ${rcvar} 549# ${command} 550# 551# stop if ${pidfile} 552# rc_pid=$(check_pidfile $pidfile $command) 553# else 554# rc_pid=$(check_process $command) 555# kill $sig_stop $rc_pid 556# wait_for_pids $rc_pid 557# ($sig_stop defaults to TERM.) 558# 559# reload Similar to stop, except use $sig_reload instead, 560# and doesn't wait_for_pids. 561# $sig_reload defaults to HUP. 562# 563# restart Run `stop' then `start'. 564# 565# status Show if ${command} is running, etc. 566# 567# poll Wait for ${command} to exit. 568# 569# rcvar Display what rc.conf variable is used (if any). 570# 571# Variables available to methods, and after run_rc_command() has 572# completed: 573# 574# Variable Purpose 575# -------- ------- 576# rc_arg Argument to command, after fast/force/one processing 577# performed 578# 579# rc_flags Flags to start the default command with. 580# Defaults to ${name}_flags, unless overridden 581# by $flags from the environment. 582# This variable may be changed by the precmd method. 583# 584# rc_pid PID of command (if appropriate) 585# 586# rc_fast Not empty if "fast" was provided (q.v.) 587# 588# rc_force Not empty if "force" was provided (q.v.) 589# 590# 591run_rc_command() 592{ 593 rc_arg=$1 594 if [ -z "$name" ]; then 595 err 3 'run_rc_command: $name is not set.' 596 fi 597 598 _rc_prefix= 599 case "$rc_arg" in 600 fast*) # "fast" prefix; don't check pid 601 rc_arg=${rc_arg#fast} 602 rc_fast=yes 603 ;; 604 force*) # "force" prefix; always run 605 rc_force=yes 606 _rc_prefix=force 607 rc_arg=${rc_arg#${_rc_prefix}} 608 if [ -n "${rcvar}" ]; then 609 eval ${rcvar}=YES 610 fi 611 ;; 612 one*) # "one" prefix; set ${rcvar}=yes 613 _rc_prefix=one 614 rc_arg=${rc_arg#${_rc_prefix}} 615 if [ -n "${rcvar}" ]; then 616 eval ${rcvar}=YES 617 fi 618 ;; 619 esac 620 621 _keywords="start stop restart rcvar" 622 if [ -n "$extra_commands" ]; then 623 _keywords="${_keywords} ${extra_commands}" 624 fi 625 rc_pid= 626 _pidcmd= 627 _procname=${procname:-${command}} 628 629 # setup pid check command if not fast 630 if [ -z "$rc_fast" ] && [ -n "$_procname" ]; then 631 if [ -n "$pidfile" ]; then 632 _pidcmd='rc_pid=$(check_pidfile '"$pidfile $_procname $command_interpreter"')' 633 else 634 _pidcmd='rc_pid=$(check_process '"$_procname $command_interpreter"')' 635 fi 636 if [ -n "$_pidcmd" ]; then 637 _keywords="${_keywords} status poll" 638 fi 639 fi 640 641 if [ -z "$rc_arg" ]; then 642 rc_usage "$_keywords" 643 fi 644 shift # remove $rc_arg from the positional parameters 645 646 if [ -n "$flags" ]; then # allow override from environment 647 rc_flags=$flags 648 else 649 eval rc_flags=\$${name}_flags 650 fi 651 eval _chdir=\$${name}_chdir _chroot=\$${name}_chroot \ 652 _nice=\$${name}_nice _user=\$${name}_user \ 653 _group=\$${name}_group _groups=\$${name}_groups \ 654 _env=\"\$${name}_env\" 655 656 if [ -n "$_user" ]; then # unset $_user if running as that user 657 if [ "$_user" = "$(id -un)" ]; then 658 unset _user 659 fi 660 fi 661 662 # if ${rcvar} is set, and $1 is not 663 # "rcvar", then run 664 # checkyesno ${rcvar} 665 # and return if that failed or warn 666 # user and exit when interactive 667 # 668 if [ -n "${rcvar}" ] && [ "$rc_arg" != "rcvar" ]; then 669 if ! checkyesno ${rcvar}; then 670 # check whether interactive or not 671 if [ -n "$_run_rc_script" ]; then 672 return 0 673 fi 674 for _elem in $_keywords; do 675 if [ "$_elem" = "$rc_arg" ]; then 676 cat 1>&2 <<EOF 677\$${rcvar} is not enabled - see ${rcvar_manpage}. 678Use the following if you wish to perform the operation: 679 $0 one${rc_arg} 680EOF 681 exit 1 682 fi 683 done 684 echo 1>&2 "$0: unknown directive '$rc_arg'." 685 rc_usage "$_keywords" 686 fi 687 fi 688 689 eval $_pidcmd # determine the pid if necessary 690 691 for _elem in $_keywords; do 692 if [ "$_elem" != "$rc_arg" ]; then 693 continue 694 fi 695 696 # if there's a custom ${XXX_cmd}, 697 # run that instead of the default 698 # 699 eval _cmd=\$${rc_arg}_cmd _precmd=\$${rc_arg}_precmd \ 700 _postcmd=\$${rc_arg}_postcmd 701 if [ -n "$_cmd" ]; then 702 # if the precmd failed and force 703 # isn't set, exit 704 # 705 if ! eval $_precmd && [ -z "$rc_force" ]; then 706 return 1 707 fi 708 709 if ! eval $_cmd \"\${@}\" && [ -z "$rc_force" ]; then 710 return 1 711 fi 712 eval $_postcmd 713 return 0 714 fi 715 716 if [ ${#} -gt 0 ]; then 717 err 1 "the $rc_arg command does not take any parameters" 718 fi 719 720 case "$rc_arg" in # default operations... 721 722 status) 723 if [ -n "$rc_pid" ]; then 724 echo "${name} is running as pid $rc_pid." 725 else 726 echo "${name} is not running." 727 return 1 728 fi 729 ;; 730 731 start) 732 if [ -n "$rc_pid" ]; then 733 echo 1>&2 "${name} already running? (pid=$rc_pid)." 734 exit 1 735 fi 736 737 if [ ! -x ${_chroot}${command} ]; then 738 return 0 739 fi 740 741 # check for required variables, 742 # directories, and files 743 # 744 for _f in $required_vars; do 745 if ! checkyesno $_f; then 746 warn "\$${_f} is not enabled." 747 if [ -z "$rc_force" ]; then 748 return 1 749 fi 750 fi 751 done 752 for _f in $required_dirs; do 753 if [ ! -d "${_f}/." ]; then 754 warn "${_f} is not a directory." 755 if [ -z "$rc_force" ]; then 756 return 1 757 fi 758 fi 759 done 760 for _f in $required_files; do 761 if [ ! -r "${_f}" ]; then 762 warn "${_f} is not readable." 763 if [ -z "$rc_force" ]; then 764 return 1 765 fi 766 fi 767 done 768 769 # if the precmd failed and force 770 # isn't set, exit 771 # 772 if ! eval $_precmd && [ -z "$rc_force" ]; then 773 return 1 774 fi 775 776 # setup the command to run, and run it 777 # 778 echo "Starting ${name}." 779 if [ -n "$_chroot" ]; then 780 _doit="\ 781$_env_clear_rc_vars $_env \ 782${_nice:+nice -n $_nice }\ 783chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\ 784$_chroot $command $rc_flags $command_args" 785 else 786 _doit="\ 787${_chdir:+cd $_chdir; }\ 788$_env_clear_rc_vars $_env \ 789${_nice:+nice -n $_nice }\ 790$command $rc_flags $command_args" 791 if [ -n "$_user" ]; then 792 _doit="su -m $_user -c 'sh -c \"$_doit\"'" 793 fi 794 fi 795 796 # if the cmd failed and force 797 # isn't set, exit 798 # 799 if ! eval $_doit && [ -z "$rc_force" ]; then 800 return 1 801 fi 802 803 # finally, run postcmd 804 # 805 eval $_postcmd 806 ;; 807 808 stop) 809 if [ -z "$rc_pid" ]; then 810 if [ -n "$pidfile" ]; then 811 echo 1>&2 \ 812 "${name} not running? (check $pidfile)." 813 else 814 echo 1>&2 "${name} not running?" 815 fi 816 exit 1 817 fi 818 819 # if the precmd failed and force 820 # isn't set, exit 821 # 822 if ! eval $_precmd && [ -z "$rc_force" ]; then 823 return 1 824 fi 825 826 # send the signal to stop 827 # 828 echo "Stopping ${name}." 829 _doit="kill -${sig_stop:-TERM} $rc_pid" 830 if [ -n "$_user" ]; then 831 _doit="su -m $_user -c 'sh -c \"$_doit\"'" 832 fi 833 834 # if the stop cmd failed and force 835 # isn't set, exit 836 # 837 if ! eval $_doit && [ -z "$rc_force" ]; then 838 return 1 839 fi 840 841 # wait for the command to exit, 842 # and run postcmd. 843 wait_for_pids $rc_pid 844 eval $_postcmd 845 ;; 846 847 reload) 848 if [ -z "$rc_pid" ]; then 849 if [ -n "$pidfile" ]; then 850 echo 1>&2 \ 851 "${name} not running? (check $pidfile)." 852 else 853 echo 1>&2 "${name} not running?" 854 fi 855 exit 1 856 fi 857 echo "Reloading ${name} config files." 858 if ! eval $_precmd && [ -z "$rc_force" ]; then 859 return 1 860 fi 861 _doit="kill -${sig_reload:-HUP} $rc_pid" 862 if [ -n "$_user" ]; then 863 _doit="su -m $_user -c 'sh -c \"$_doit\"'" 864 fi 865 if ! eval $_doit && [ -z "$rc_force" ]; then 866 return 1 867 fi 868 eval $_postcmd 869 ;; 870 871 restart) 872 if ! eval $_precmd && [ -z "$rc_force" ]; then 873 return 1 874 fi 875 # prevent restart being called more 876 # than once by any given script 877 # 878 if ${_rc_restart_done:-false}; then 879 return 0 880 fi 881 _rc_restart_done=true 882 883 ( $0 ${_rc_prefix}stop ) 884 $0 ${_rc_prefix}start 885 886 eval $_postcmd 887 ;; 888 889 poll) 890 if [ -n "$rc_pid" ]; then 891 wait_for_pids $rc_pid 892 fi 893 ;; 894 895 rcvar) 896 echo "# $name" 897 if [ -n "$rcvar" ]; then 898 if checkyesno ${rcvar}; then 899 echo "${rcvar}=YES" 900 else 901 echo "${rcvar}=NO" 902 fi 903 fi 904 ;; 905 906 *) 907 rc_usage "$_keywords" 908 ;; 909 910 esac 911 return 0 912 done 913 914 echo 1>&2 "$0: unknown directive '$rc_arg'." 915 rc_usage "$_keywords" 916 exit 1 917} 918 919# 920# _have_rc_postprocessor 921# Test whether the current script is running in a context that 922# was invoked from /etc/rc with a postprocessor. 923# 924# If the test fails, some variables may be unset to make 925# such tests more efficient in future. 926# 927_have_rc_postprocessor() 928{ 929 # Cheap tests that fd and pid are set, fd is writable. 930 [ -n "${_rc_pid}" ] || { unset _rc_pid; return 1; } 931 [ -n "${_rc_postprocessor_fd}" ] || { unset _rc_pid; return 1; } 932 eval ": >&${_rc_postprocessor_fd}" 2>/dev/null \ 933 || { unset _rc_pid; return 1; } 934 935 return 0 936} 937 938# 939# run_rc_script file arg 940# Start the script `file' with `arg', and correctly handle the 941# return value from the script. If `file' ends with `.sh', it's 942# sourced into the current environment. If `file' appears to be 943# a backup or scratch file, ignore it. Otherwise if it's 944# executable run as a child process. 945# 946# If `file' contains "KEYWORD: interactive" and if we are 947# running inside /etc/rc with postprocessing, then the script's 948# stdout and stderr are redirected to $_rc_original_stdout_fd and 949# $_rc_original_stderr_fd, so the output will be displayed on the 950# console but not intercepted by /etc/rc's postprocessor. 951# 952run_rc_script() 953{ 954 _file=$1 955 _arg=$2 956 if [ -z "$_file" ] || [ -z "$_arg" ]; then 957 err 3 'USAGE: run_rc_script file arg' 958 fi 959 960 _run_rc_script=true 961 962 unset name command command_args command_interpreter \ 963 extra_commands pidfile procname \ 964 rcvar required_dirs required_files required_vars 965 eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd 966 967 _must_redirect=false 968 if _have_rc_postprocessor \ 969 && _has_rcorder_keyword interactive $_file 970 then 971 _must_redirect=true 972 fi 973 974 case "$_file" in 975 *.sh) # run in current shell 976 if $_must_redirect; then 977 print_rc_metadata \ 978 "note:Output from ${_file} is not logged" 979 no_rc_postprocess eval \ 980 'set $_arg ; . $_file' 981 else 982 set $_arg ; . $_file 983 fi 984 ;; 985 *[~#]|*.OLD|*.orig|*,v) # scratch file; skip 986 warn "Ignoring scratch file $_file" 987 ;; 988 *) # run in subshell 989 if [ -x $_file ] && $_must_redirect; then 990 print_rc_metadata \ 991 "note:Output from ${_file} is not logged" 992 if [ -n "$rc_fast_and_loose" ]; then 993 no_rc_postprocess eval \ 994 'set $_arg ; . $_file' 995 else 996 no_rc_postprocess eval \ 997 '( set $_arg ; . $_file )' 998 fi 999 elif [ -x $_file ]; then 1000 if [ -n "$rc_fast_and_loose" ]; then 1001 set $_arg ; . $_file 1002 else 1003 ( set $_arg ; . $_file ) 1004 fi 1005 else 1006 warn "Ignoring non-executable file $_file" 1007 fi 1008 ;; 1009 esac 1010} 1011 1012# 1013# load_rc_config command 1014# Source in the configuration file for a given command. 1015# 1016load_rc_config() 1017{ 1018 _command=$1 1019 if [ -z "$_command" ]; then 1020 err 3 'USAGE: load_rc_config command' 1021 fi 1022 1023 if ${_rc_conf_loaded:-false}; then 1024 : 1025 else 1026 . /etc/rc.conf 1027 _rc_conf_loaded=true 1028 fi 1029 if [ -f /etc/rc.conf.d/"$_command" ]; then 1030 . /etc/rc.conf.d/"$_command" 1031 fi 1032} 1033 1034# 1035# load_rc_config_var cmd var 1036# Read the rc.conf(5) var for cmd and set in the 1037# current shell, using load_rc_config in a subshell to prevent 1038# unwanted side effects from other variable assignments. 1039# 1040load_rc_config_var() 1041{ 1042 if [ $# -ne 2 ]; then 1043 err 3 'USAGE: load_rc_config_var cmd var' 1044 fi 1045 eval $(eval '( 1046 load_rc_config '$1' >/dev/null; 1047 if [ -n "${'$2'}" ] || [ "${'$2'-UNSET}" != "UNSET" ]; then 1048 echo '$2'=\'\''${'$2'}\'\''; 1049 fi 1050 )' ) 1051} 1052 1053# 1054# rc_usage commands 1055# Print a usage string for $0, with `commands' being a list of 1056# valid commands. 1057# 1058rc_usage() 1059{ 1060 echo -n 1>&2 "Usage: $0 [fast|force|one](" 1061 1062 _sep= 1063 for _elem; do 1064 echo -n 1>&2 "$_sep$_elem" 1065 _sep="|" 1066 done 1067 echo 1>&2 ")" 1068 exit 1 1069} 1070 1071# 1072# err exitval message 1073# Display message to stderr and log to the syslog, and exit with exitval. 1074# 1075err() 1076{ 1077 exitval=$1 1078 shift 1079 1080 if [ -x /usr/bin/logger ]; then 1081 logger "$0: ERROR: $*" 1082 fi 1083 echo 1>&2 "$0: ERROR: $*" 1084 exit $exitval 1085} 1086 1087# 1088# warn message 1089# Display message to stderr and log to the syslog. 1090# 1091warn() 1092{ 1093 if [ -x /usr/bin/logger ]; then 1094 logger "$0: WARNING: $*" 1095 fi 1096 echo 1>&2 "$0: WARNING: $*" 1097} 1098 1099# 1100# backup_file action file cur backup 1101# Make a backup copy of `file' into `cur', and save the previous 1102# version of `cur' as `backup' or use rcs for archiving. 1103# 1104# This routine checks the value of the backup_uses_rcs variable, 1105# which can be either YES or NO. 1106# 1107# The `action' keyword can be one of the following: 1108# 1109# add `file' is now being backed up (and is possibly 1110# being reentered into the backups system). `cur' 1111# is created and RCS files, if necessary, are 1112# created as well. 1113# 1114# update `file' has changed and needs to be backed up. 1115# If `cur' exists, it is copied to to `back' or 1116# checked into RCS (if the repository file is old), 1117# and then `file' is copied to `cur'. Another RCS 1118# check in done here if RCS is being used. 1119# 1120# remove `file' is no longer being tracked by the backups 1121# system. If RCS is not being used, `cur' is moved 1122# to `back', otherwise an empty file is checked in, 1123# and then `cur' is removed. 1124# 1125# 1126backup_file() 1127{ 1128 _action=$1 1129 _file=$2 1130 _cur=$3 1131 _back=$4 1132 1133 if checkyesno backup_uses_rcs; then 1134 _msg0="backup archive" 1135 _msg1="update" 1136 1137 # ensure that history file is not locked 1138 if [ -f $_cur,v ]; then 1139 rcs -q -u -U -M $_cur 1140 fi 1141 1142 # ensure after switching to rcs that the 1143 # current backup is not lost 1144 if [ -f $_cur ]; then 1145 # no archive, or current newer than archive 1146 if [ ! -f $_cur,v ] || [ $_cur -nt $_cur,v ]; then 1147 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur 1148 rcs -q -kb -U $_cur 1149 co -q -f -u $_cur 1150 fi 1151 fi 1152 1153 case $_action in 1154 add|update) 1155 cp -p $_file $_cur 1156 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur 1157 rcs -q -kb -U $_cur 1158 co -q -f -u $_cur 1159 chown root:wheel $_cur $_cur,v 1160 ;; 1161 remove) 1162 cp /dev/null $_cur 1163 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur 1164 rcs -q -kb -U $_cur 1165 chown root:wheel $_cur $_cur,v 1166 rm $_cur 1167 ;; 1168 esac 1169 else 1170 case $_action in 1171 add|update) 1172 if [ -f $_cur ]; then 1173 cp -p $_cur $_back 1174 fi 1175 cp -p $_file $_cur 1176 chown root:wheel $_cur 1177 ;; 1178 remove) 1179 mv -f $_cur $_back 1180 ;; 1181 esac 1182 fi 1183} 1184 1185# 1186# handle_fsck_error fsck_exit_code 1187# Take action depending on the return code from fsck. 1188# 1189handle_fsck_error() 1190{ 1191 case $1 in 1192 0) # OK 1193 return 1194 ;; 1195 2) # Needs re-run, still fs errors 1196 echo "File system still has errors; re-run fsck manually!" 1197 ;; 1198 4) # Root modified 1199 echo "Root file system was modified, rebooting ..." 1200 reboot -n 1201 echo "Reboot failed; help!" 1202 ;; 1203 8) # Check failed 1204 echo "Automatic file system check failed; help!" 1205 ;; 1206 12) # Got signal 1207 echo "Boot interrupted." 1208 ;; 1209 *) 1210 echo "Unknown error $1; help!" 1211 ;; 1212 esac 1213 stop_boot 1214} 1215 1216# 1217# _has_rcorder_keyword word file 1218# Check whether a file contains a "# KEYWORD:" comment with a 1219# specified keyword in the style used by rcorder(8). 1220# 1221_has_rcorder_keyword() 1222{ 1223 local word="$1" 1224 local file="$2" 1225 local line 1226 1227 [ -r "$file" ] || return 1 1228 while read line; do 1229 case "${line} " in 1230 "# KEYWORD:"*[\ \ ]"${word}"[\ \ ]*) 1231 return 0 1232 ;; 1233 "#"*) 1234 continue 1235 ;; 1236 *[A-Za-z0-9]*) 1237 # give up at the first non-empty non-comment line 1238 return 1 1239 ;; 1240 esac 1241 done <"$file" 1242 return 1 1243} 1244 1245# 1246# print_rc_metadata string 1247# Print the specified string in such a way that the post-processor 1248# inside /etc/rc will treat it as meta-data. 1249# 1250# If we are not running inside /etc/rc, do nothing. 1251# 1252# For public use by any rc.d script, the string must begin with 1253# "note:", followed by arbitrary text. The intent is that the text 1254# will appear in a log file but not on the console. 1255# 1256# For private use within /etc/rc, the string must contain a 1257# keyword recognised by the rc_postprocess_metadata() function 1258# defined in /etc/rc, followed by a colon, followed by one or more 1259# colon-separated arguments associated with the keyword. 1260# 1261print_rc_metadata() 1262{ 1263 # _rc_postprocessor fd, if defined, is the fd to which we must 1264 # print, prefixing the output with $_rc_metadata_prefix. 1265 # 1266 if _have_rc_postprocessor; then 1267 command printf "%s%s\n" "$rc_metadata_prefix" "$1" \ 1268 >&${_rc_postprocessor_fd} 1269 fi 1270} 1271 1272# 1273# _flush_rc_output 1274# Arrange for output to be flushed, if we are running 1275# inside /etc/rc with postprocessing. 1276# 1277_flush_rc_output() 1278{ 1279 print_rc_metadata "nop" 1280} 1281 1282# 1283# print_rc_normal [-n] string 1284# Print the specified string in such way that it is treated as 1285# normal output, regardless of whether or not we are running 1286# inside /etc/rc with post-processing. 1287# 1288# If "-n" is specified in $1, then the string in $2 is printed 1289# without a newline; otherwise, the string in $1 is printed 1290# with a newline. 1291# 1292# Intended use cases include: 1293# 1294# o An rc.d script can use ``print_rc_normal -n'' to print a 1295# partial line in such a way that it appears immediately 1296# instead of being buffered by rc(8)'s post-processor. 1297# 1298# o An rc.d script that is run via the no_rc_postprocess 1299# function (so most of its output is invisible to rc(8)'s 1300# post-processor) can use print_rc_normal to force some of its 1301# output to be seen by the post-processor. 1302# 1303# 1304print_rc_normal() 1305{ 1306 # print to stdout or _rc_postprocessor_fd, depending on 1307 # whether not we have an rc postprocessor. 1308 # 1309 local fd=1 1310 _have_rc_postprocessor && fd="${_rc_postprocessor_fd}" 1311 case "$1" in 1312 "-n") 1313 command printf "%s" "$2" >&${fd} 1314 _flush_rc_output 1315 ;; 1316 *) 1317 command printf "%s\n" "$1" >&${fd} 1318 ;; 1319 esac 1320} 1321 1322# 1323# no_rc_postprocess cmd... 1324# Execute the specified command in such a way that its output 1325# bypasses the post-processor that handles the output from 1326# most commands that are run inside /etc/rc. If we are not 1327# inside /etc/rc, then just execute the command without special 1328# treatment. 1329# 1330# The intent is that interactive commands can be run via 1331# no_rc_postprocess(), and their output will apear immediately 1332# on the console instead of being hidden or delayed by the 1333# post-processor. An unfortunate consequence of the output 1334# bypassing the post-processor is that the output will not be 1335# logged. 1336# 1337no_rc_postprocess() 1338{ 1339 if _have_rc_postprocessor; then 1340 "$@" >&${_rc_original_stdout_fd} 2>&${_rc_original_stderr_fd} 1341 else 1342 "$@" 1343 fi 1344} 1345 1346# 1347# twiddle 1348# On each call, print a different one of "/", "-", "\\", "|", 1349# followed by a backspace. The most recently printed value is 1350# saved in $_twiddle_state. 1351# 1352# Output is to /dev/tty, so this function may be useful even inside 1353# a script whose output is redirected. 1354# 1355twiddle() 1356{ 1357 case "$_twiddle_state" in 1358 '/') _next='-' ;; 1359 '-') _next='\' ;; 1360 '\') _next='|' ;; 1361 *) _next='/' ;; 1362 esac 1363 command printf "%s\b" "$_next" >/dev/tty 1364 _twiddle_state="$_next" 1365} 1366 1367# 1368# human_exit_code 1369# Print the a human version of the exit code. 1370# 1371human_exit_code() 1372{ 1373 if [ "$1" -lt 127 ] 1374 then 1375 echo "exited with code $1" 1376 elif [ "$(expr $1 % 256)" -eq 127 ] 1377 then 1378 # This cannot really happen because the shell will not 1379 # pass stopped job status out and the exit code is limited 1380 # to 8 bits. This code is here just for completeness. 1381 echo "stopped with signal $(expr $1 / 256)" 1382 else 1383 echo "terminated with signal $(expr $1 - 128)" 1384 fi 1385} 1386 1387# 1388# collapse_backslash_newline 1389# Copy input to output, collapsing <backslash><newline> 1390# to nothing, but leaving other backslashes alone. 1391# 1392collapse_backslash_newline() 1393{ 1394 local line 1395 while read -r line ; do 1396 case "$line" in 1397 *\\) 1398 # print it, without the backslash or newline 1399 command printf "%s" "${line%?}" 1400 ;; 1401 *) 1402 # print it, with a newline 1403 command printf "%s\n" "${line}" 1404 ;; 1405 esac 1406 done 1407} 1408 1409# Shell implementations of basename and dirname, usable before 1410# the /usr file system is mounted. 1411# 1412basename() 1413{ 1414 local file="$1" 1415 local suffix="$2" 1416 local base 1417 1418 base="${file##*/}" # remove up to and including last '/' 1419 base="${base%${suffix}}" # remove suffix, if any 1420 command printf "%s\n" "${base}" 1421} 1422 1423dirname() 1424{ 1425 local file="$1" 1426 local dir 1427 1428 case "$file" in 1429 /*/*) dir="${file%/*}" ;; # common case: absolute path 1430 /*) dir="/" ;; # special case: name in root dir 1431 */*) dir="${file%/*}" ;; # common case: relative path with '/' 1432 *) dir="." ;; # special case: name without '/' 1433 esac 1434 command printf "%s\n" "${dir}" 1435} 1436 1437# Override the normal "echo" and "printf" commands, so that 1438# partial lines printed by rc.d scripts appear immediately, 1439# instead of being buffered by rc(8)'s post-processor. 1440# 1441# Naive use of the echo or printf commands from rc.d scripts, 1442# elsewhere in rc.subr, or anything else that sources rc.subr, 1443# will call these functions. To call the real echo and printf 1444# commands, use "command echo" or "command printf". 1445# 1446# Avoid use of echo altogether as much as possible, printf works better 1447# 1448echo() 1449{ 1450 local IFS=' ' NL='\n' # not a literal newline... 1451 1452 case "$1" in 1453 -n) NL=; shift;; 1454 esac 1455 1456 command printf "%s${NL}" "$*" 1457 1458 if test -z "${NL}" 1459 then 1460 _flush_rc_output 1461 fi 1462 return 0 1463} 1464 1465printf() 1466{ 1467 command printf "$@" 1468 case "$1" in 1469 *'\n') : ;; 1470 *) _flush_rc_output ;; 1471 esac 1472 return 0 1473} 1474 1475kat() { 1476 local i 1477 local v 1478 for i; do 1479 while read -r v; do 1480 v="${v%%#*}" 1481 if [ -z "$v" ]; then 1482 continue 1483 fi 1484 echo "$v" 1485 done < "$i" 1486 done 1487} 1488 1489_rc_subr_loaded=: 1490