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