]> TLD Linux GIT Repositories - rc-scripts.git/blob - lib/functions
25803f6557872a00e4f4d30de2f2228a28760150
[rc-scripts.git] / lib / functions
1 #!/bin/sh - keep it for file(1) to get bourne shell script result
2 # functions     This file contains functions to be used by most or all
3 #               shell scripts in the /etc/rc.d/init.d directory.
4 #
5 #
6 # Author:       Miquel van Smoorenburg, <miquels@drinkel.nl.mugnet.org>
7 # Hacked by:    Greg Galloway and Marc Ewing
8 # Modified for PLD Linux by:
9 #               Marek Obuchowicz <elephant@pld-linux.org>
10 #               Arkadiusz Miśkiewicz <misiek@pld-linux.org>
11 #               Michał Kochanowicz <mkochano@pld-linux.org>
12 #               Łukasz Pawelczyk <havner@pld-linux.org>
13 # Modified for TLD Linux by:
14 #               Marcin Krol <hawk@tld-linux.org>
15
16 # First set up a default search path.
17 export PATH="/sbin:/usr/sbin:/bin:/usr/bin"
18
19 # Set defaults
20 if [ -z "$COLUMNS" -o -z "$LINES" ]; then
21         _setterm() {
22                 set -- $(stty size 2>/dev/null)
23                 LINES=${LINES:-$1}
24                 COLUMNS=${COLUMNS:-$2}
25         }
26         _setterm
27         unset _setterm
28 fi
29 [ -z "$LINES" ] || [ "$LINES" -le 0 ] && LINES=40
30 [ -z "$COLUMNS" ] || [ "$COLUMNS" -le 0 ] && COLUMNS=80
31 export LINES COLUMNS
32 INIT_COL=$((COLUMNS - 13))
33
34 # Set colors
35 RED=1
36 GREEN=2
37 YELLOW=3
38 BLUE=4
39 MAGENTA=5
40 CYAN=6
41 WHITE=7
42 # Bold definition (second parameter to termput setaf)
43 BOLD=1
44 NOBOLD=0
45 # Default colors
46 CBRACKETS="$CYAN"       # brackets [ ] color
47 CDONE="$GREEN"          # DONE and WORK color
48 CBUSY="$MAGENTA"        # BUSY color
49 CFAIL="$RED"            # FAIL and DIED color
50 CPOWEREDBY="$CYAN"      # "Powered by" color
51 CTLD="$GREEN"           # "TLD Linux" color
52 CI="$RED"               # Capital I color (press I to enter interactive startup)
53 CRESMAN="$GREEN"        # "Resource Manager" color
54 CHARS=""                # Characters displayed on the beginning of show line
55 CCHARS="$WHITE"         # Color of these characters (look at /etc/sysconfig/init-colors.gentoo example)
56
57 # Source configuration if available - may override default values
58 [ -r /etc/sysconfig/init-colors ] && . /etc/sysconfig/init-colors
59 [ -r /etc/sysconfig/system ] && . /etc/sysconfig/system
60 [ -r /etc/sysconfig/bootsplash ] && . /etc/sysconfig/bootsplash
61
62 # we need to know in functions if we were called from a terminal
63 if [ -z "$ISATTY" ]; then
64         [ -t ] && ISATTY=yes || ISATTY=no
65         export ISATTY
66 fi
67
68 is_yes() {
69         # Test syntax
70         if [ $# = 0 ]; then
71                 msg_usage " is_yes {value}"
72                 return 2
73         fi
74
75         # Check value
76         case "$1" in
77         yes|Yes|YES|true|True|TRUE|on|On|ON|Y|y|1)
78                 # true returns zero
79                 return 0
80                 ;;
81         *)
82                 # false returns one
83                 return 1
84                 ;;
85         esac
86 }
87
88 is_no() {
89         # Test syntax
90         if [ $# = 0 ]; then
91                 msg_usage " is_no {value}"
92                 return 2
93         fi
94
95         case "$1" in
96         no|No|NO|false|False|FALSE|off|Off|OFF|N|n|0)
97                 # true returns zero
98                 return 0
99                 ;;
100         *)
101                 # false returns one
102                 return 1
103                 ;;
104         esac
105 }
106
107 # checks if file is empty
108 # empty lines and lines beginning with hash are ignored
109 is_empty_file() {
110         [ -s "$1" ] || return 0
111         grep -vqE "^(#|[[:blank:]]*$)" "$1" && return 1 || return 0
112 }
113
114 # returns OK if $1 contains $2
115 strstr() {
116         [ "${1#*$2*}" = "$1" ] && return 1
117         return 0
118 }
119
120 # Apply sysctl settings, including files in /etc/sysctl.d
121 apply_sysctl() {
122         sysctl -q -e --system
123 }
124
125 if is_yes "$FASTRC" || is_yes "$IN_SHUTDOWN"; then
126         RC_LOGGING=no
127 fi
128
129 if is_no "$RC_LOGGING"; then
130         initlog() {
131                 RESULT=0
132                 while [ "$1" != "${1##-}" ]; do
133                         case $1 in
134                         -c)
135                                 shift
136                                 $1
137                                 RESULT=$?
138                                 break
139                                 ;;
140                         *)
141                                 shift
142                                 ;;
143                         esac
144                 done
145                 return $RESULT
146         }
147 fi
148
149 kernelver() {
150         local _x _y _z v v1 old_IFS ver
151         {
152                 read _x _y v _z
153                 old_IFS=$IFS
154                 # strip _* or -* from versions like: "2.6.25_vanilla-1", "2.6.25-1"
155                 IFS='_-'
156                 set -- $v
157                 v1=${1}
158                 IFS='.'
159                 set -- $v1
160                 IFS=$old_IFS
161
162                 ver=${3}
163                 while [ ${#ver} -lt 3 ]; do ver="0$ver"; done
164                 ver="$2$ver"
165                 while [ ${#ver} -lt 6 ]; do ver="0$ver"; done
166                 ver="$1$ver"
167                 while [ ${#ver} -lt 9 ]; do ver="0$ver"; done
168                 echo $ver
169         } < /proc/version
170 }
171
172 kernelverser() {
173         local _x _y _z v v1 old_IFS ver
174         {
175                 read _x _y v _z
176                 old_IFS=$IFS
177                 # strip _* or -* from versions like: "2.6.25_vanilla-1", "2.6.25-1"
178                 IFS='_-'
179                 set -- $v
180                 v1=${1}
181                 IFS='.'
182                 set -- $v1
183                 IFS=$old_IFS
184                 ver=$2
185                 while [ ${#ver} -lt 3 ]; do ver="0$ver"; done
186                 ver="$1$ver"
187                 while [ ${#ver} -lt 6 ]; do ver="0$ver"; done
188                 echo $ver
189         } </proc/version
190 }
191
192 kernelvermser() {
193         local _x _y _z v v1 old_IFS ver
194         {
195                 read _x _y v _z
196                 old_IFS=$IFS
197                 # strip _* or -* from versions like: "2.6.25_vanilla-1", "2.6.25-1"
198                 IFS='_-'
199                 set -- $v
200                 v1=${1}
201                 IFS='.'
202                 set -- $v1
203                 IFS=$old_IFS
204                 ver="$1"
205                 while [ ${#ver} -lt 3 ]; do ver="0$ver"; done
206                 echo $ver
207         } </proc/version
208 }
209
210 # Colors workaround
211 termput() {
212         is_yes "$ISATTY" || return
213
214         if is_yes "$FASTRC" || is_no "$TPUT"; then
215                 case "$1" in
216                 hpa)
217                         echo -ne "\033[$(($2+1))G"
218                         ;;
219                 cuu*)
220                         echo -ne "\033[${2}A"
221                         ;;
222                 el)
223                         echo -ne "\033[0K"
224                         ;;
225                 setaf)
226                         local ISBOLD
227                         if [ -n "$3" ]; then
228                                 ISBOLD="$3"
229                         else
230                                 ISBOLD="$NOBOLD";
231                         fi
232                         is_yes "$COLOR_INIT" && echo -ne "\033[${ISBOLD};3${2}m"
233                         ;;
234                 op)
235                         echo -ne "\033[0m"
236                         ;;
237                 esac
238         else
239                 case "$1" in
240                 hpa | cuu* | el)
241                         tput "$@"
242                         ;;
243                 setaf)
244                         if [ "$3" = "1" ]; then tput bold; else tput sgr0; fi
245                         is_yes "$COLOR_INIT" && tput setaf "$2"
246                         ;;
247                 op)
248                         tput sgr0
249                         ;;
250                 esac
251         fi
252 }
253
254 if [ ! -x /bin/printf ]; then
255         # printf equivalent
256         # FIXME: buggy when single or double quotes in message!
257         printf() {
258                 local text m
259                 text="$1"
260                 shift
261                 if [ $# -gt 0 ]; then
262                         m="$1"
263                         shift
264                         while [ $# -gt 0 ]; do
265                                 m="$m\",\"$1"
266                                 shift
267                         done
268                 fi
269                 awk "BEGIN {printf \"$text\", \"$m\"; }"
270         }
271 fi
272
273 # National language support function
274 nls() {
275         local msg_echo nls_domain text message
276         msg_echo='\n'
277         nls_domain="$NLS_DOMAIN"
278         while [ "$1" != "${1##-}" ]; do
279                 case "$1" in
280                 --nls-domain)
281                         shift
282                         nls_domain="$1"
283                         shift
284                         ;;
285                 -n)
286                         msg_echo=''
287                         shift
288                         ;;
289                 esac
290         done
291         message="$1"
292         shift
293
294         # empty message, so we return --misiek
295         if [ -z "$message" ]; then
296                 echo -en "$msg_echo"
297                 return
298         fi
299
300         if is_yes "$GETTEXT"; then
301                 message=$(TEXTDOMAINDIR="/etc/sysconfig/locale" gettext -e --domain="${nls_domain:-rc-scripts}" "$message")
302         fi
303
304         printf "$message" "$@"
305         echo -en "$msg_echo"
306 }
307
308 rc_splash() {
309         local action="$1"
310
311         if ! is_no "$BOOT_SPLASH"; then
312                 [ -x /bin/splash ] && /bin/splash "$action"
313         fi
314
315         : $((progress++))
316 }
317
318 msg_network_down() {
319         nls "ERROR: Networking is down. %s can't be run." "$1" >&2
320 }
321
322 msg_starting() {
323         show "Starting %s service" "$1"
324 }
325
326 msg_already_running() {
327         nls "%s service is already running." "$1"
328 }
329
330 msg_stopping() {
331         show "Stopping %s service" "$1"
332 }
333
334 msg_not_running() {
335         nls "%s service is not running." "$1"
336 }
337
338 msg_reloading() {
339         show "Reloading %s service" "$1"
340 }
341
342 msg_usage() {
343         nls "Usage: %s" "$*"
344 }
345
346 # Some functions to handle TLD Linux-style messages
347 show() {
348         local text len time
349
350         if is_yes "$RC_UPTIME"; then
351                 time=$(awk '{printf("[%8.2f] ", $1)}' /proc/uptime)
352         fi
353
354         if is_no "$FASTRC" && is_yes "$GETTEXT"; then
355                 text=$time$(nls -n "$@")
356         else
357                 text=$time$(printf "$@")
358         fi
359         len=${#text}
360         while [ $((len++)) -lt $INIT_COL ]; do
361                 text="$text."
362         done
363         if [ -n "$CHARS" ]; then
364                 termput setaf $CCHARS
365                 echo -n "$CHARS"
366                 termput op
367         fi
368         echo -n "$text"
369 }
370
371 deltext() {
372         termput hpa $INIT_COL
373 }
374
375 # Displays message in square brackests ("[ DONE ]"). Takes two arguments.
376 # First is the text to display, second is color number to use (argument to
377 # tput setaf). If second argument is not given, default (2, green) will be
378 # used).
379 progress() {
380         local COLOR
381         if [ -n "$2" ]; then
382                 COLOR="$2"
383         else
384                 COLOR="$CDONE"
385         fi
386         deltext
387         echo -n "$(termput setaf $CBRACKETS)[$(termput setaf $COLOR) $(nls --nls-domain rc-scripts "$1") $(termput setaf $CBRACKETS)]$(termput op)"
388 }
389
390 busy() {
391         echo -n "$_busy"
392 }
393
394 ok() {
395         echo "$_ok"
396 }
397
398 started() {
399         echo "$_started"
400 }
401
402 fail() {
403         echo "$_fail"
404         return 1
405 }
406
407 died() {
408         echo "$_died"
409         return 1
410 }
411
412 # Check if $pid (could be plural) are running
413 checkpid() {
414         while [ "$1" ]; do
415                 [ -d "/proc/$1" ] && return 0
416                 shift
417         done
418         return 1
419 }
420
421 # - outside chroot get only those processes, which are outside chroot.
422 # - inside chroot get only those processes, which are inside chroot.
423 # - don't filter out pids which do not have corresponding running processes (process died etc)
424 # (note: some processes like named are chrooted but run outside chroot)
425 filter_chroot() {
426         # no pids, exit early
427         [ $# -eq 0 ] && return
428
429         # filter by pid namespace if such dir exists for current process
430         # we do filter in containers as stacked containers are possible with LXC
431         if [ -d /proc/$$/ns ]; then
432                 local pids
433                 pids=$(filter_ns "$@") && set -- "$pids"
434         fi
435
436         if [ $# -lt 1 -o ! -d /proc/1 ]; then
437                 echo $@
438                 return
439         fi
440
441         local root_dir good_pids="" good_add_pid
442         for root_pid in $@; do
443                 root_dir=$(resolvesymlink /proc/${root_pid}/root)
444                 if [ -n "$root_dir" ]; then
445                         good_add_pid=1
446                         if [ -n "${SYSTEM_CHROOTS}" ]; then
447                                 for r_dir in ${SYSTEM_CHROOTS}; do
448                                         echo "$root_dir" | grep -q "^${r_dir}" && good_add_pid=0
449                                 done
450                         fi
451                         [ "$good_add_pid" -eq 1 ] && good_pids="$good_pids $root_pid"
452                 elif [ ! -d "/proc/$root_pid" ]; then
453                         good_pids="$good_pids $root_pid"
454                 fi
455         done
456         echo $good_pids
457 }
458
459 # similar to filter_chroot, but filter based on /proc/PID/ns/pid value
460 filter_ns() {
461         local cur_ns=$(resolvesymlink /proc/$$/ns/pid)
462         [ "$cur_ns" ] || return 1
463
464         local pid ns pids=""
465         # add pids if it matches current pid namespace
466         # we should add pids what do not exist (dead processes),
467         # but not add pids whose namespace does not match
468         # (processes belonging to different NS do exist in /proc)
469         for pid in "$@"; do
470                 if [ ! -d /proc/$pid ]; then
471                         pids="$pids $pid"
472                         continue
473                 fi
474                 ns=$(resolvesymlink /proc/$pid/ns/pid)
475                 if [ "$ns" = "$cur_ns" ]; then
476                         pids="$pids $pid"
477                 fi
478         done
479         echo $pids
480         return 0
481 }
482
483 # Usage:
484 # run_cmd Message command_to_run
485 # run_cmd -a Message command_to_run
486 # run_cmd --user "username" "Message" command_to_run
487 run_cmd() {
488         local force_err=0 exit_code=0 errors user
489         while [ $# -gt 0 ]; do
490                 case "$1" in
491                 -a)
492                         force_err=1
493                         ;;
494                 --user)
495                         shift
496                         user=$1
497                         ;;
498                 *)
499                         break
500                 esac
501                 shift
502         done
503
504         local message=$1; shift
505         show "$message"; busy
506
507         if errors=$(
508                 cd /
509                 export HOME=/tmp TMPDIR=/tmp
510                 if is_no "$RC_LOGGING"; then
511                         ${user:+setuidgid -s $user} eval "$@" 2>&1
512                 else
513                         ${user:+setuidgid -s $user} initlog -c "$*" 2>&1
514                 fi
515                 ); then
516                 ok
517                 log_success "$1 $message"
518         else
519                 fail
520                 log_failed "$1 $message"
521                 exit_code=1
522         fi
523         [ -n "$errors" ] && [ $exit_code -eq 1 -o $force_err -eq 1 ] && echo "$errors"
524         return $exit_code
525 }
526
527 _daemon_set_ulimits() {
528         local opt val ksh=${KSH_VERSION:+1}
529         set -- ${SERVICE_LIMITS:-$DEFAULT_SERVICE_LIMITS}
530         while [ $# -gt 0 ]; do
531                 opt=$1
532                 val=$2
533                 if [ "$ksh" ]; then
534                         case "$opt" in
535                         -Hu)
536                                 opt=-Hp
537                         ;;
538                         -Su)
539                                 opt=-Sp
540                         ;;
541                         -u)
542                                 opt=-p
543                         ;;
544                         esac
545                 fi
546                 ulimit $opt $val
547                 shift 2
548         done
549 }
550
551 # inner function used by daemon().
552 # do not call this directly, as it expects variables being inherited.
553 # also it expects to be called from subshell as it exports env.
554 # it expects options parsed by daemon() and command to be executed in "$@".
555 _daemon_exec() {
556         local prog=""
557         umask ${SERVICE_UMASK:-$DEFAULT_SERVICE_UMASK};
558         export USER=root HOME=/tmp TMPDIR=/tmp
559
560         nice=${nice:-$DEFAULT_SERVICE_RUN_NICE_LEVEL}
561         nice=${nice:-0}
562
563         # make nice level absolute, not to be dependant of nice level of shell where service started
564         nice=$(($nice - $(nice)))
565
566         if [ "$closefds" = 1 ]; then
567                 exec 1>&-
568                 exec 2>&-
569                 exec 0<&-
570         elif [ "$redirfds" = 1 ]; then
571                 exec 1>/dev/null
572                 exec 2>/dev/null
573                 exec 0</dev/null
574         else
575                 exec 2>&1
576                 exec 0</dev/null
577         fi
578
579         if is_no "$RC_LOGGING"; then
580                 prog=$1; shift
581                 if [ ! -x $prog ]; then
582                         logger -t rc-scripts -p daemon.debug "daemon: Searching PATH for $prog, consider using full path in initscript"
583                         local a o=$IFS
584                         IFS=:
585                         for a in $PATH; do
586                                 if [ -x $a/$prog ]; then
587                                         prog=$a/$prog
588                                         break
589                                 fi
590                         done
591                         IFS=$o
592                 fi
593                 set -- "$prog" "$@"
594
595                 # use setsid to detach from terminal,
596                 # NOTE: setsid needs to be "outer" program
597                 # otherwise start-stop-daemon would capture the setsid pid not the actual program
598
599                 prog=$1; shift
600                 /usr/bin/setsid \
601                 /sbin/start-stop-daemon -q --start \
602                         --nicelevel $nice \
603                         ${pidfile:+--pidfile $pidfile} \
604                         ${makepid:+--make-pidfile} \
605                         ${user:+--chuid $user} \
606                         ${chdir:+--chdir "$chdir"} \
607                         ${fork:+--background} \
608                         ${SERVICE_DROPCAPS:+--dropcap $SERVICE_DROPCAPS} \
609                         --exec "$prog" \
610                         -- "$@"
611         else
612                 if [ "$fork" = "1" ]; then
613                         export PIDFILE="/dev/null"
614                         if [ "$makepid" ] && [ "$pidfile" ]; then
615                                 export PIDFILE="$pidfile"
616                         fi
617                         set -- /lib/rc-scripts/makepid "$@"
618                         set -- /usr/bin/setsid "$@"
619                 fi
620                 if [ -n "$user" -a "$user" != "root" ]; then
621                         set -- /bin/runuser -u "$user" -- "$@"
622                 fi
623
624                 nice -n $nice initlog -c "$*" 2>&1 </dev/null
625         fi
626 }
627
628 # A function to start a program (now it's useful on read-only filesystem too)
629 daemon() {
630         local errors="" waitname="" waittime=0
631         local exit_code=0
632         local nice=$SERVICE_RUN_NICE_LEVEL
633         local fork user closefds redirfds pidfile makepid chdir=/
634
635         while [ $# -gt 0 ]; do
636                 case $1 in
637                 '')
638                 msg_usage " daemon [--check] [--user user] [--fork] [--chdir directory] [--closefds] [--redirfds] [--waitforname procname] [--waitfortime seconds] [--pidfile file] [--makepid] [+/-nicelevel] {program} <program args>"
639                         return 2
640                         ;;
641                 --check)
642                         # for compatibility with redhat/mandrake
643                         nls "warning: --check option is ignored!"
644                         shift
645                         ;;
646                 --user)
647                         shift
648                         user=$1
649                         ;;
650                 --fork)
651                         fork=1
652                         ;;
653                 --chdir)
654                         shift
655                         chdir=$1
656                         ;;
657                 --closefds)
658                         closefds=1
659                         ;;
660                 --redirfds)
661                         redirfds=1
662                         ;;
663                 --waitforname)
664                         shift
665                         waitname="$1"
666                         ;;
667                 --waitfortime)
668                         shift
669                         waittime="$1"
670                         ;;
671                 --pidfile=?*)
672                         pidfile="${1#--pidfile=}"
673                         case "$pidfile" in /*);; *) pidfile="/var/run/$pidfile";; esac
674                         ;;
675                 --pidfile)
676                         shift
677                         pidfile="$1"
678                         case "$pidfile" in /*);; *) pidfile="/var/run/$pidfile";; esac
679                         ;;
680                 --makepid)
681                         makepid=1
682                         # makepid implies fork
683                         fork=1
684                         ;;
685                 -*|+*)
686                         nice=$1
687                         shift
688                         break
689                         ;;
690                 *)
691                         break
692                         ;;
693                 esac
694                 shift
695         done
696
697         _daemon_set_ulimits
698
699         [ -z "$DEFAULT_SERVICE_UMASK" ] && DEFAULT_SERVICE_UMASK=022
700         [ -z "$DEFAULT_SERVICE_RUN_NICE_LEVEL" ] && DEFAULT_SERVICE_RUN_NICE_LEVEL=0
701
702         # And start it up.
703         busy
704         cd $chdir
705         [ -n "$SERVICE_CPUSET" ] && is_yes "$CPUSETS" && echo $$ > "/dev/cpuset/${SERVICE_CPUSET}/tasks"
706         if errors=$(_daemon_exec "$@"); then
707                 # wait for process (or pidfile) to be created
708                 if [ "$waittime" -gt 0 ]; then
709                         # waitname can be empty, as if pidfile is in use, it is not relevant
710                         waitproc "$waittime" "$waitname" "$pidfile"
711                 fi
712                 log_success "$1 startup"
713                 ok
714         else
715                 exit_code=1
716                 fail
717                 log_failed "$1 startup"
718                 [ -n "$errors" ] && echo >&2 "$errors"
719         fi
720         return $exit_code
721 }
722
723 # wait (in seconds) for process (or pidfile) to be created
724 # example: waitproc 30 httpd /var/run/httpd.pid
725 waitproc() {
726         local waittime=$1 procname=$2 pidfile=$3
727         local pid
728         local now=$(date +%s)
729         local maxtime=$(($now + $waittime))
730
731         if [ -z "$procname" -a -z "$pidfile" ]; then
732                 msg_usage "waitproc: procname or pidfile must be specified"
733                 return 2
734         fi
735
736         while [ "$(date +%s)" -lt "$maxtime" ]; do
737                 pid=$(pidofproc "$procname" "$pidfile")
738                 [ -n "$pid" ] && break
739
740                 # start-stop-daemon uses same delay
741                 usleep 20000
742         done
743 }
744
745 # A function to stop a program.
746 killproc() {
747         local notset killlevel base pid pidfile result delay=3 try
748         # Test syntax.
749         if [ $# = 0 ]; then
750                 msg_usage " killproc [--pidfile|-p PIDFILE] [-d DELAY] {program} [-SIGNAME]"
751                 return 2
752         fi
753
754         while [ "$1" != "${1##-}" ]; do
755                 case $1 in
756                 -d)
757                         delay="$2"
758                         shift 2
759                         ;;
760                 --pidfile|-p)
761                         pidfile="$2"
762                         case "$pidfile" in /*);; *) pidfile="/var/run/$pidfile";; esac
763                         shift 2
764                         ;;
765                 --waitforname)
766                         waitname="$2"
767                         shift 2
768                         ;;
769                 --waitfortime)
770                         waittime="$2"
771                         shift 2
772                         ;;
773                 esac
774         done
775
776         busy
777
778         local notset=0
779         # check for second arg to be kill level
780         if [ -n "$2" ]; then
781                 killlevel=$2
782         else
783                 notset=1
784         fi
785
786         # experimental start-stop-daemon based killing.
787         # works only with pidfile
788         if is_no "$RC_LOGGING" && [ "$pidfile" ]; then
789                 local sig=${killlevel:--TERM} retry
790                 # do not retry if signal is specified,
791                 # as otherwise impossible to send HUP if process pid stays in pidfile.
792                 # however, do retry if --waitfortime was specified
793                 if [ "${killlevel+set}" = "set" ] && [ -z "$waittime" ]; then
794                         # if we send HUP it's ok if process does not die
795                         retry="--oknodo"
796                 else
797                         local waitretry
798                         : ${waittime=10}
799                         : ${waitretry=$(($waittime * 2))}
800
801                         # 1. kill with $sig, wait $delay
802                         # 2. kill with $sig, wait $waittime
803                         # 3. kill with KILL, wait $waitretry
804                         retry="--retry ${sig#-}/${delay}/${sig#-}/${waittime}/KILL/${waitretry}"
805                 fi
806                 /sbin/start-stop-daemon -q --stop \
807                         $retry \
808                         ${waitname:+--name $waitname} \
809                         -s ${sig#-} \
810                         ${pidfile:+--pidfile $pidfile}
811                 result=$?
812                 if [ "$result" -eq 0 ]; then
813                         ok
814                 else
815                         fail
816                 fi
817                 return $result
818         fi
819
820
821         # Save basename.
822         base=${1##*/}
823
824         # Find pid.
825         pid=$(pidofproc "$1" "$pidfile")
826         [ -z "$pid" ] && pid=$(pidofproc "$base" "$pidfile")
827
828         # Kill it.
829         if [ -n "$pid" -a "$pid" != "$$" ] && checkpid $pid 2>&1; then
830                 if [ "$notset" = "1" ]; then
831                         if checkpid $pid 2>&1; then
832                                 # TERM first, then KILL if not dead
833                                 kill -TERM $pid
834                                 usleep 50000
835
836                                 try=0
837                                 while [ $try -lt $delay ]; do
838                                         checkpid $pid || break
839                                         sleep 1
840                                         try=$((try+1))
841                                 done
842                                 if checkpid $pid; then
843                                         # XXX: SIGKILL is sent already on 4th second!
844                                         # HARMFUL for example to mysqld (which is already workarounded)
845                                         kill -KILL $pid
846                                         usleep 50000
847                                 fi
848                         fi
849                         checkpid $pid
850                         result=$?
851                         if [ "$result" -eq 0 ]; then
852                                 fail
853                                 log_failed "$1 shutdown"
854                         else
855                                 ok
856                                 log_success "$1 shutdown"
857                         fi
858                         result=$(( ! $result ))
859                 else
860                         # use specified level only
861                         if checkpid $pid > /dev/null 2>&1; then
862                                 kill $killlevel $pid
863                                 result=$?
864                                 if [ "$result" -eq 0 ]; then
865                                         ok
866                                         log_success "$1 got $killlevel"
867                                 else
868                                         result=7
869                                         fail
870                                         log_failed "$1 didn't get $killlevel"
871                                 fi
872                         else
873                                 result=7
874                                 died
875                                 log_failed "$1 shutdown"
876                         fi
877                 fi
878         else
879                 died
880                 log_failed "$1 shutdown"
881                 result=7
882         fi
883
884         if [ -n "$waitname" -a -n "$waittime" ]; then
885                 # Save basename.
886                 base=${waitname##*/}
887                 # Find pid.
888                 pid=$(pidofproc "$waitname" "$pidfile")
889                 [ -z "$pid" ] && pid=$(pidofproc "$base" "$pidfile")
890                 i=0
891                 while [ "$i" -lt "$waittime" ]; do
892                         i=$(( i + 1 ))
893                         checkpid $pid && sleep 1 || break
894                 done
895         fi
896
897         # Remove pid file if any.
898         if [ "$notset" = "1" ]; then
899                 rm -f /var/run/${base}.pid
900         fi
901
902         return $result
903 }
904
905 # A function to find the pid of a program.
906 pidofproc() {
907         local pid pidfile base=${1##*/}
908         pidfile="$base.pid"
909         [ -n "$2" ] && pidfile="$2"
910
911         # Test syntax.
912         if [ $# = 0 ]; then
913                 msg_usage " pidofproc {program}"
914                 return 2
915         fi
916
917         # First try pidfile or "/var/run/*.pid"
918         case "$pidfile" in
919                 /*)pidfile="${pidfile}";;
920                 *) pidfile="/var/run/$pidfile";;
921         esac
922         if [ -f "${pidfile}" ]; then
923                 local p
924                 for p in $(< "${pidfile}"); do
925                         [ -z "$(echo "$p" | awk '{gsub(/[0-9]/,"");print;}')" ] && pid="$pid $p"
926                 done
927         else
928                 unset pidfile
929         fi
930
931         # Next try "pidof" if pidfile is not specified
932         if [ -z "$pid" ] && [ -z "$2" ]; then
933                 pid=$(pidof -o $$ -o $PPID -o %PPID -x "$1")
934         fi
935
936         pid=$(filter_chroot $pid)
937         echo $pid
938 }
939
940 # status [--pidfile PIDFILE] {subsys} [{daemon}]"
941 status() {
942         local pid subsys daemon cpuset_msg pidfile
943         if [ "$1" = "--pidfile" -o "$1" = "-p" ]; then
944                 pidfile=$2
945                 case "$pidfile" in /*);; *) pidfile="/var/run/$pidfile";; esac
946                 shift 2
947         fi
948
949         subsys=$1
950         daemon=${2:-$subsys}
951
952         # Test syntax.
953         if [ $# = 0 ]; then
954                 msg_usage " status [--pidfile PIDFILE] {subsys} [{daemon}]"
955                 return 2
956         fi
957
958         # if pidfile specified, pid must be there
959         if [ "$pidfile" ]; then
960                 [ -f "$pidfile" ] && read pid < $pidfile
961                 # filter_chroot does not filter out dead pids, so this extra check, see t/status-pidfile.sh
962                 if [ ! -d "/proc/$pid" ]; then
963                         pid=
964                 fi
965         else
966                 pid=$(pidof -o $$ -o $PPID -o %PPID -x $daemon)
967         fi
968         pid=$(filter_chroot $pid)
969
970         if [ "$pid" ]; then
971                 cpuset_msg="..."
972                 if [ -n "$SERVICE_CPUSET" ] && is_yes "$CPUSETS"; then
973                         if grep -q "$pid" "/dev/cpuset/${SERVICE_CPUSET}/tasks"; then
974                                 cpuset_msg=$(nls " in cpuset %s..." "$SERVICE_CPUSET")
975                         else
976                                 cpuset_msg=$(nls " outside of configured cpuset %s..." "$SERVICE_CPUSET")
977                         fi
978                 fi
979                 nls "%s (pid %s) is running%s" "$daemon" "$pid" "$cpuset_msg"
980                 return 0
981         fi
982
983         # Next try "/var/run/*.pid" files; if pidfile is not set
984         local base=${daemon##*/}
985         if [ -z "$pidfile" -a -f /var/run/${base}.pid ]; then
986                 read pid < /var/run/${base}.pid
987                 pid=$(filter_chroot $pid)
988                 if [ "$pid" ]; then
989                         nls "%s dead but pid file (%s) exists" "$subsys" /var/run/${base}.pid
990                         return 1
991                 fi
992         fi
993
994         # See if /var/lock/subsys/$subsys exists
995         if [ -f /var/lock/subsys/$subsys ]; then
996                 nls "daemon %s dead but subsys (%s) locked" "$daemon" "$subsys"
997                 return 2
998         fi
999         nls "%s is stopped" "$subsys"
1000         return 3
1001 }
1002
1003 # Confirm whether we really want to run this service
1004 confirm() {
1005         local answer
1006         nls -n "Start service %s (Y)es/(N)o/(C)ontinue? [Y] " "$1"
1007         read answer
1008         case $answer in
1009         y|Y|t|T|j|J|"")
1010                 return 0
1011                 ;;
1012         c|C|k|K|w|W)
1013                 return 2
1014                 ;;
1015         n|N)
1016                 return 1
1017                 ;;
1018         *)
1019                 confirm $1
1020                 return $?
1021                 ;;
1022         esac
1023 }
1024
1025 # module is needed (ie. is requested, is available and isn't loaded already)
1026 is_module() {
1027         # fail if /sbin/lsmod does not exists (ex. in containers)
1028         [ -x /sbin/lsmod ] || return 1
1029
1030         # module name without .o at end
1031         if ! lsmod | grep -q "$1"; then
1032                 if ls -1R /lib/modules/$(uname -r)/ 2> /dev/null | grep -q "^${1}.\(\|k\)o\(\|.gz\)"; then
1033                         # true
1034                         return 0
1035                 fi
1036         fi
1037         # false
1038         return 1
1039 }
1040
1041 _modprobe() {
1042         local parsed single die args foo result
1043         parsed=no
1044         while is_no "$parsed"; do
1045                 case "$1" in
1046                 "single")
1047                         single=yes
1048                         shift
1049                         ;;
1050                 "die")
1051                         die=yes
1052                         shift
1053                         ;;
1054                 -*)
1055                         args="$args $1"
1056                         shift
1057                         ;;
1058                 *)
1059                         parsed=yes
1060                         ;;
1061                 esac
1062         done
1063         if is_yes "${single}"; then
1064                 foo="$@"
1065                 show "Loading %s kernel module(s)" "$foo"
1066                 busy
1067         fi
1068         if [ -x /sbin/modprobe ]; then
1069                 /sbin/modprobe -s $args "$@"
1070                 result=$?
1071         else
1072                 deltext; fail
1073                 result=1
1074         fi
1075         if is_yes "${single}"; then
1076                 deltext
1077                 if [ $result = "0" ]; then
1078                         is_yes "$single" && ok
1079                 else
1080                         fail
1081                         if is_yes "$die"; then
1082                                 nls "Could not load %s kernel module(s)" "$@"
1083                                 exit 1
1084                         fi
1085                 fi
1086         fi
1087 }
1088
1089 if is_no "$RC_LOGGING"; then
1090         log_success() {
1091                 :
1092         }
1093
1094         log_failed() {
1095                 :
1096         }
1097 else
1098         log_success() {
1099                 initlog -n $0 -s "$1 $2" -e 1
1100         }
1101
1102         log_failed() {
1103                 initlog -n $0 -s "$1 $2" -e 2
1104         }
1105 fi
1106
1107 # Check if any flavor of portmapper is running
1108 check_portmapper() {
1109         if [ -x /usr/sbin/rpcinfo ]; then
1110                 if /usr/sbin/rpcinfo -p localhost >/dev/null 2>/dev/null; then
1111                         return 0
1112                 else
1113                         return 1
1114                 fi
1115         elif [ -z "$(pidof portmap)" -a -z "$(pidof rpcbind)" ]; then
1116                 return 1
1117         fi
1118         return 0
1119 }
1120
1121 # is_fsmounted fstype mntpoint
1122 # Check if filesystem fstype is mounted on mntpoint
1123 is_fsmounted() {
1124         local fstype=$1
1125         local mntpoint=$2
1126
1127         [ -n "$fstype" -a -n "$mntpoint" ] || return 1
1128
1129         if [ -r /proc/mounts ]; then
1130                 grep -qE "[[:blank:]]$mntpoint[[:blank:]]+$fstype[[:blank:]]" /proc/mounts
1131                 return $?
1132         else
1133                 if [ "$(stat -L -f -c %T $mntpoint 2>/dev/null)" = "$fstype" ]; then
1134                         return 0
1135                 else
1136                         return 1
1137                 fi
1138         fi
1139 }
1140
1141 # __umount_loop awk_program fstab_file first_msg retry_msg umount_args
1142 # awk_program should process fstab_file and return a list of fstab-encoded
1143 # paths; it doesn't have to handle comments in fstab_file.
1144 __umount_loop() {
1145         local remaining sig=
1146         local retry=3 count
1147
1148         remaining=$(LC_ALL=C awk "/^#/ {next} $1" "$2" | sort -r)
1149         while [ -n "$remaining" -a "$retry" -gt 0 ]; do
1150                 if [ "$retry" -eq 3 ]; then
1151                         run_cmd "$3" fstab-decode umount $5 $remaining
1152                 else
1153                         run_cmd "$4" fstab-decode umount $5 $remaining
1154                 fi
1155                 count=4
1156                 remaining=$(LC_ALL=C awk "/^#/ {next} $1" "$2" | sort -r)
1157                 while [ "$count" -gt 0 ]; do
1158                         [ -z "$remaining" ] && break
1159                         count=$(($count-1))
1160                         usleep 500000
1161                         remaining=$(LC_ALL=C awk "/^#/ {next} $1" "$2" | sort -r)
1162                 done
1163                 [ -z "$remaining" ] && break
1164                 fstab-decode /bin/fuser -k -m $sig $remaining >/dev/null
1165                 sleep 3
1166                 retry=$(($retry -1))
1167                 sig=-9
1168         done
1169 }
1170
1171 # Similar to __umount loop above, specialized for loopback devices
1172 __umount_loopback_loop() {
1173         local remaining devremaining sig=
1174         local retry=3
1175
1176         remaining=$(awk '$1 ~ /^\/dev\/loop/ && $2 != "/" {print $2}' /proc/mounts)
1177         devremaining=$(awk '$1 ~ /^\/dev\/loop/ && $2 != "/" {print $1}' /proc/mounts)
1178         while [ -n "$remaining" -a "$retry" -gt 0 ]; do
1179                 if [ "$retry" -eq 3 ]; then
1180                         run_cmd "Unmounting loopback filesystems: " \
1181                                 fstab-decode umount $remaining
1182                 else
1183                         run_cmd "Unmounting loopback filesystems (retry):" \
1184                                 fstab-decode umount $remaining
1185                 fi
1186                 for dev in $devremaining ; do
1187                         losetup $dev > /dev/null 2>&1 && \
1188                                 run_cmd "Detaching loopback device $dev: " \
1189                                 losetup -d $dev
1190                 done
1191                 remaining=$(awk '$1 ~ /^\/dev\/loop/ && $2 != "/" {print $2}' /proc/mounts)
1192                 devremaining=$(awk '$1 ~ /^\/dev\/loop/ && $2 != "/" {print $1}' /proc/mounts)
1193                 [ -z "$remaining" ] && break
1194                 fstab-decode /bin/fuser -k -m $sig $remaining >/dev/null
1195                 sleep 3
1196                 retry=$(($retry -1))
1197                 sig=-9
1198         done
1199 }
1200
1201 rc_cache_init() {
1202         # If we have cachefile, use it.
1203         # If we don't, create memory variables and try to save silently,
1204         local cachefile='/var/cache/rc-scripts/msg.cache'
1205
1206         local term
1207         if is_yes "$ISATTY"; then
1208                 term=$TERM
1209         else
1210                 term=dumb
1211         fi
1212
1213         # We create $check variable which is used to invalidate the cache.
1214         # The $check contains user locale and terminal.
1215         local check="$term.$LC_MESSAGES.$INIT_COL"
1216
1217         if [ -f "$cachefile" -a "$cachefile" -nt /etc/sysconfig/system -a "$cachefile" -nt /etc/sysconfig/init-colors ]; then
1218                 if . "$cachefile" 2>/dev/null; then
1219                         if [ "$check" = "$_check" ]; then
1220                                 return
1221                         fi
1222                 fi
1223         fi
1224
1225         # primitive caching
1226         _busy=$(progress "BUSY" "$CBUSY")
1227         _ok=$(progress "DONE")
1228         _started=$(progress "WORK")
1229         _fail=$(progress "FAIL" "$CFAIL")
1230         _died=$(progress "DIED" "$CFAIL")
1231
1232         # we don't use heredoc, as ksh attempts to create tempfile then
1233         (> "$cachefile" ) 2>/dev/null || return
1234         echo "_busy='$_busy';" >> "$cachefile"
1235         echo "_ok='$_ok';" >> "$cachefile"
1236         echo "_started='$_started';" >> "$cachefile"
1237         echo "_fail='$_fail';" >> "$cachefile"
1238         echo "_died='$_died';" >> "$cachefile"
1239         echo "_check='$check';" >> "$cachefile"
1240 }
1241
1242 rc_gettext_init() {
1243         if [ -z "$GETTEXT" ]; then
1244                 if [ -x /bin/gettext -o -x /usr/bin/gettext ]; then
1245                         GETTEXT=yes
1246                 else
1247                         GETTEXT=no
1248                 fi
1249         fi
1250
1251         if [ -z "$TPUT" ]; then
1252                 if [ -d /usr/share/terminfo ] && [ -x /usr/bin/tput -o -x /bin/tput ]; then
1253                         TPUT=yes
1254                         # check if we are on proper terminal
1255                         tput longname >/dev/null 2>&1 || TPUT=no
1256                 else
1257                         TPUT=no
1258                 fi
1259         fi
1260 }
1261
1262 rc_gettext_init
1263 rc_cache_init
1264
1265 #/*
1266 # * Local variables:
1267 # * mode: sh
1268 # * indent-tabs-mode: notnil
1269 # * End:
1270 # *
1271 # */