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