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