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