reimplemented service routines
[grml-shlib.git] / sh-lib
1 #!/bin/sh
2 # Filename:      sh-lib
3 # Purpose:       Shellscript library
4 # Authors:       grml-team (grml.org), (c) Michael Gebetsroither <gebi@grml.org>
5 # Bug-Reports:   see http://grml.org/bugs/
6 # License:       This file is licensed under the GPL v2.
7 # Latest change: Mon May 02 00:17:44 CEST 2005 [gebi]
8 ################################################################################
9
10
11 VERBOSE__=0
12 VERBOSE_TMP__=0
13
14 # FIXME maybe PROG_PATH__ for better error reporting?
15 PROG_NAME__=""    # initialised within init section
16
17 # directory for init scripts
18 INITD_DIR__="/etc/init.d/"
19
20 # >= level and the function will print the message
21 EPRINT__=1    # eprint (error print)
22 EEPRINT__=2   # 2print (intern error print)
23 DPRINT__=3    # dprint (debug print)
24
25 EXIT_FUNCTION__="_syslog"    # function to call upon die (can be set by user)
26
27 SYSLOG__="YES"
28
29 CMD_LINE__=""   # /proc/cmdline
30
31 LANG__="$LANG"
32 LC_ALL__="$LC_ALL"
33
34
35 # CONFIG FUNCTIONS  {{{
36
37 function setProgName  { PROG_NAME__="$1"; }
38
39 function setExitFunction  { EXIT_FUNCTION__="$1"; }
40
41 function disableSyslog  { SYSLOG__="NO";  }
42 function enableSyslog   { SYSLOG__="YES"; }
43
44 function saveLang { LANG__="$LANG"; LC_ALL__="$LC_ALL"; }
45 function restoreLang { LANG="$LANG__"; LC_ALL="$LC_ALL__"; }
46 function setCLang { saveLang; LANG="C"; LC_ALL="C"; }
47 # }}}
48
49
50 # DEBUG FRAMEWORK  {{{
51
52 function setVerbose     { VERBOSE__=${1:-1}; }
53 function unsetVerbose   { VERBOSE_TMP__=$VERBOSE__; VERBOSE__=0; }
54 function restoreVerbose { VERBOSE__=$VERBOSE_TMP__; }
55 function getVerbose     { echo "$VERBOSE__"; }
56
57 function setDebug       { setVerbose "$DPRINT__"; }
58 function unsetDebug     { restoreVerbose; }
59
60 function setExitFunction    { EXIT_FUNCTION__="$1"; }
61 function resetExitFunction  { EXIT_FUNCTION__="_syslog"; }
62 # }}}
63
64
65 # ERROR REPORTING FUNCTIONS  {{{
66
67 # default print backend (there may be other functions)
68 function vprint
69 {
70   local level_="$1"
71   local type_="$2"
72   local message_="$3"
73   
74   if [ $VERBOSE__ -ge $level_ -a -n "$message_" ]; then
75     echo -n "$type_" >&2
76     echo "$message_" >&2
77   fi
78 }
79
80 # print error output
81 function eprint
82 {
83   # FIXME vprint should be a var, because we want to call user-defined functions
84   # global var (there should be a syslog, and vprint + syslog function)
85   vprint $EPRINT__ "Error - " "$1"
86 }
87
88 # should be used for intern silentExecutes
89 function eeprint
90 {
91   vprint $EEPRINT__ "  Error2 - " "$1"
92 }
93
94 # print debug output (function intern errors)
95 function dprint
96 {
97   vprint $DPRINT__ "Debug - " "$1"
98 }
99
100 # for program notice messages
101 function notice
102 {
103   vprint $EPRINT__ "Notice - " "$1"
104 }
105
106 function die
107 {
108   local error_message_="$1"   # print this error message
109   local exit_code_="$2"  # command exited with this exit code
110
111   echo -n "PANIC: $error_message_" >&2
112   if [ -n "$2" ]; then
113     echo "; ret($exit_code_)" >&2
114   else
115     echo >&2
116   fi
117
118   if [ -n "$EXIT_FUNCTION__" ]; then
119     $EXIT_FUNCTION__ "$error_message_" "$exit_code_" >&2
120   fi
121   kill $$
122 }
123
124 function warn
125 {
126   local error_message_="$1"   # print this error message
127   local exit_code_="$2"  # command exits with this exit code
128
129   echo -n "WARN: $error_message_" >&2
130   if [ -n "$exit_code_" ]; then
131     echo "; ret($exit_code_)" >&2
132   else
133     echo >&2
134   fi
135 }
136
137 function _syslog
138 {
139   local message_="$1"   # error message
140   local exit_code_="$2"
141
142   if [ "$SYSLOG__" = "YES" ]; then
143     if [ -n "$exit_code_" ]; then
144       logger -p user.alert -t "$PROG_NAME__" -i "$message_ ret($exit_code_)" >&2
145     else
146       logger -p user.alert -t "$PROG_NAME__" -i "$message_" >&2
147     fi
148   fi
149 }
150
151 function syslog
152 {
153   local message_="$1"   # error message
154   local exit_code_="$2"
155   
156   if [ -n "$exit_code_" ]; then
157     logger -p user.alert -t "$PROG_NAME__" -i "$message_ ret($exit_code_)" >&2
158   else
159     logger -p user.alert -t "$PROG_NAME__" -i "$message_" >&2
160   fi
161 }
162
163 function warnLog
164 {
165   local error_message_="$1"   # print this error message
166   local exit_code_="$2"  # command exits with this exit code
167
168   warn "$error_message_" "$exit_code_"
169   syslog "$error_message_" "$exit_code_"
170 }
171 # }}}
172
173
174 ###
175 #
176 # CORE FUNCTIONS
177 #
178 ###
179
180 # i don't want to write exit status controle stuff every time
181 function execute
182 {
183   local to_exec_="$1"   # command to execute
184   local error_function_=${2:-"eprint"}    # function to call on error
185   local message_="$3"   # user supplied error message
186
187   local ret_=''
188
189   eval "$to_exec_"
190   ret_=$?
191
192   if [ $ret_ -eq 127 ]; then
193     syslog "problems executing ( $to_exec_ )" $ret_
194   fi
195   if [ $ret_ -ne 0 ]; then
196     if [ -z "$message_" ]; then
197       $error_function_ "problems executing ( $to_exec_ )" "$ret_"
198     else
199       $error_function_ "$message_" "$ret_"
200     fi
201   fi
202   dprint "exec-$error_function_: ( $to_exec_ ) ret($ret_)"
203   return $ret_
204 }
205
206 function silentExecute
207 {
208   unsetVerbose
209   execute "$@"
210   local ret_=$?
211   restoreVerbose
212   return $ret_
213 }
214
215
216 ###
217 #
218 # TEST FUNCTIONS
219 #
220 ###
221
222 # if the file DOES exist, everything is fine
223 function isExistent
224 {
225   local file_to_test_="$1"    # file to test
226   local error_function_=${2:-"eprint"}    # function to call on error
227   local message_="$3"    # user supplied error message
228
229   if [ ! -e "$file_to_test_" ]; then
230     if [ -z "$message_" ]; then
231       $error_function_ "file does not exist \"$file_to_test_\"" 66
232     else
233       $error_function_ "$message_"
234     fi
235     return 1
236   fi
237   dprint "isExistent(): file \"$1\" does exist => ready to go"
238   return 0
239 }
240
241 function isNotExistent
242 {
243   local file_to_test_="$1"    # file to test
244   local error_function_=${2:-"eprint"}    # function to call on error
245   local message_="$3"    # user supplied error message
246
247   if [ -e "$file_to_test_" ]; then
248     if [ -z "$message_" ]; then
249       $error_function_ "file does allready exist \"$file_to_test_\"" 67
250     else
251       $error_function_ "$message_"
252     fi
253     return 1
254   fi
255   dprint "isNotExistent(): file \"$1\" does not exist => ready to go"
256   return 0
257 }
258
259
260 function checkUser
261 {
262   local to_check_="$1"    # username to check against running process
263   local error_function_=${2:-"eprint"}    # function to call on error
264   local message_="$3"    # user supplied error message
265
266   local user_=''
267
268   user_=`id -un`
269   if [ $user_ != "$to_check_" ]; then
270     if [ -z "$message_" ]; then
271       $error_function_ "username \"$user_\" is not \"$to_check_\"" 77 $exit_function_
272     else
273       $error_function_ "$message_"
274     fi
275     return 1
276   else
277     dprint "checkUser(): accepted, username matches \"$to_check_\""
278     return 0
279   fi
280 }
281
282 function checkId
283 {
284   local to_check_="$1"    # user-id to check against running process
285   local error_function_=${2:-"eprint"}    # function to call on error
286   local message_="$3"    # user supplied error message
287
288   local user_id_=''
289
290   user_id_=`id -u`
291   if [ $user_id_ != "$to_check_" ]; then
292     if [ -z "$message_" ]; then
293       $error_function_ "UID \"$user_id_\" is not \"$to_check_\"" 77
294     else
295       $error_function_ "$message_"
296     fi
297     return 1
298   else
299     dprint "checkId(): accepted, UID matches \"$to_check_\""
300     return 0
301   fi
302 }
303
304 function checkRoot
305 {
306   checkId 0 "$1" "$2"
307 }
308
309
310 function runsFromHd
311 {
312   if [ -e "/etc/grml_cd" ]; then
313     dprint "runsFromHd(): grml is on CD"
314     return 1
315   else
316     dprint "runsFromHd(): grml is on HD"
317     return 0
318   fi
319 }
320
321 function runsFromCd
322 {
323   if [ -e "/etc/grml_cd" ]; then
324     dprint "runsFromCd(): grml is on CD"
325     return 0
326   else
327     dprint "runsFromCd(): grml is on HD"
328     return 1
329   fi
330 }
331
332
333 # secure input from console
334 function secureInput
335 {
336   local to_secure_="$1"
337   
338   local secured_=''
339
340   secured_=`echo -n "$to_secure_" |tr -c '[:alnum:]/.\-,\(\)' '_'`
341   dprint "secureInput(): \"$to_secure_\" => \"$secured_\""
342   echo "$secured_"
343 }
344
345
346 # convert all possible path formats to absolute paths
347 function relToAbs
348 {
349   local relpath_="$1"
350
351   local D_=''
352   local B_=''
353   local abspath_=''
354   local end_path_=''
355
356   D_=`dirname "$relpath_"`
357   B_=`basename "$relpath_"`
358   abspath_=`cd "$D_" 2>/dev/null && pwd || echo "$D_"`/$B_
359   end_path_=`echo "$abspath_" |tr --squeeze-repeats /`
360   dprint "relToAbs(): \"$relpath_\" => \"$end_path_\""
361   echo "$end_path_"
362 }
363
364 # Simple shell grep
365 function stringInFile
366 {
367   local to_test_="$1"   # matching pattern
368   local source_="$2"    # source-file to grep
369
370   if [ ! -e "$source_" ]; then
371     eprint "stringInFile(): \"$source_\" does not exist"
372     return 1
373   fi
374
375   case "$(cat $source_)" in *$to_test_*) return 0;; esac
376   return 1
377 }
378
379 # same for strings
380 function stringInString
381 {
382   local to_test_="$1"   # matching pattern
383   local source_="$2"    # string to search in
384
385   case "$source_" in *$to_test_*) return 0;; esac
386   return 1
387 }
388
389 # get value for bootparam given as first param
390 function getBootParam
391 {
392   local param_to_search_="$1"
393   local result_=''
394
395   stringInString " $param_to_search_=" "$CMD_LINE__" || return 1
396   result_="${CMD_LINE__##*$param_to_search_=}"
397   result_="${result_%%[   ]*}"
398   echo "$result_"
399   return 0
400 }
401
402 # Check boot commandline for specified option
403 function checkBootParam
404 {
405   stringInString " $1" "$CMD_LINE__"
406   return "$?"
407 }
408
409
410 # NETWORK  {{{
411
412 # validates an IP FIXME
413 function netValidIp
414 {
415   local ip_="$1"    # ip addresse to validate
416   local error_function_=${2:-"eprint"}    # function to call on error
417   local message_="$3"    # user supplied error message
418   
419   local ret_=''
420
421   echo "$ip_" | grep -E -q -e '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}.[0-9]{1,3}' \
422     &>/dev/null
423   ret_=$?
424   if [ $ret_ -ne 0 ]; then
425     if [ -z "$message_" ]; then
426       "$error_function_" "ip-addresse \"$ip_\" is NOT valied" $ret_
427     else
428       "$error_function_" "$message_" $ret_
429     fi
430     return 1
431   fi
432
433   dprint "ip-addresse \"$ip_\" is valied" $ret_
434   return $ret_
435 }
436
437 function netGetIfaces
438 {
439   local error_function_=${1:-"eprint"}    # function to call on error
440   local message_="$2"    # user supplied error message
441   local if_=''
442   local ret_=''
443
444   #ip a|grep 'inet ' |awk '$NF !~ /lo/{print $NF}'
445   if_="`ip a|grep 'inet ' |awk '{print $NF}'`"
446   ret_=$?
447   if [ -z "$if_" ]; then
448     if [ -z "$message_" ]; then
449       "$error_function_" "no interfaces found" $ret_
450     else
451       "$error_function_" "$message_" $ret_
452     fi
453     return 1
454   fi
455   dprint "interfaces found" $ret_
456   echo "$if_"
457 }
458
459 # FIXME
460 function netGetDefaultGateway
461 {
462   local error_function_=${1:-"eprint"}    # function to call on error
463   local message_="$2"    # user supplied error message
464   
465   local ip_=''
466   local ret_=''
467   
468   setCLang
469   ip_=`route -n | awk '/^0\.0\.0\.0/{print $2; exit}'`
470   ret_=$?
471   restoreLang
472   if [ -z "$ip_" ]; then
473     if [ -z "$message_" ]; then
474       "$error_function_" "no default gateway found" $ret_
475     else
476       "$error_function_" "$message_" $ret_
477     fi
478     return 1
479   fi
480   dprint "default gateway is \"$ip_\"" $ret_
481   echo "$ip_"
482   return 0
483 }
484
485 # FIXME
486 function netGetNetmask
487 {
488   local iface_="$1"
489   local error_function_=${2:-"eprint"}    # function to call on error
490   local message_="$3"    # user supplied error message
491   
492   local nm_=''
493   local ret_=''
494   
495   setCLang
496   nm_=`ifconfig "$iface_" | awk '/[Mm]ask/{FS="[:   ]*"; $0=$0; print $8; exit}'`
497   ret_=$?
498   restoreLang
499   if [ -z "$nm_" ]; then
500     if [ -z "$message_" ]; then
501       "$error_function_" "could not find a netmask for \"$iface_\"" $ret_
502     else 
503       "$error_function_" "$message_" $ret_
504     fi
505     return 1
506   fi
507   dprint "netmask on \"$iface_\" is \"$nm_\"" $ret_
508   echo "$nm_"
509   return 0
510 }
511
512 # FIXME
513 function netGetIp
514 {
515   local iface_="$1"
516   local error_function_=${2:-"eprint"}    # function to call on error
517   local message_="$3"    # user supplied error message
518
519   local ip_=""
520   local ret_=""
521
522   setCLang
523   #ip_=`ip addr list eth0 |mawk '/inet/{split($2,A,"/"); print A[1]}'`
524   ip_=`ifconfig "$iface_" | awk '/[Ii]net [Aa]ddr/{FS="[:  ]*"; $0=$0; print $4; exit}'`
525   ret_=$?
526   restoreLang
527   if [ -z "$ip_" ]; then
528     if [ -z "$message_" ]; then
529       "$error_function_" "no ip for \"$iface_\" found" $ret_
530     else
531       "$error_function_" "$message_" $ret_
532     fi
533     return 1
534   fi
535   dprint "addresse for \"$iface_\" is \"$ip_\"" $ret_
536   echo "$ip_"
537   return 0
538
539
540 function netGetNameservers
541 {
542   local error_function_=${1:-"eprint"}    # function to call on error
543   local message_="$2"    # user supplied error message
544   
545   local file_="/etc/resolv.conf"
546   local ns_=""
547
548   if [ ! -e $file_ ]; then
549     warn "file \"$file_\" does not exist, could not get nameservers"
550     return 1
551   fi
552   
553   setCLang
554   ns_=`awk '/^nameserver/{printf "%s ",$2}' $file_`
555   restoreLang
556   if [ -z "$ns_" ]; then
557     if [ -z "$message_" ]; then
558       "$error_function_" "no nameservers found" $ret_
559     else
560       "$error_function_" "$message_" $ret_
561     fi
562     return 1
563   fi
564   dprint "nameservers: \"$ns_\"" $ret_
565   echo "$ns_"
566   return 0
567 }
568
569 # }}}
570
571 # SERVICES {{{
572 function _touchService
573 {
574   local action_="${1:-start}"
575   local service_="$2"
576   local error_function_=${3:-"eprint"}    # function to call on error
577   local message_="$4"     # user supplied error message
578
579   local i=""
580   local known_action_='false'
581   for i in "start" "stop" "restart" "reload" "force-reload"; do
582     if [[ $i == $action_ ]]; then
583       known_action_='true'
584       break
585     fi
586   done
587   $known_action_ || warn "_touchService(): unknown action \"$action_\""
588
589
590   local service_path_=""
591   service_path_="${INITD_DIR__}/$service_"
592   if [ ! -e "$service_path_" ]; then
593     warn "_touchService(): service does not exist: \"$service_\""
594     return 1
595   fi
596   if [ ! -x "$service_path_" ]; then
597     warn "_touchService(): service is not executable: \"$service_\""
598   fi
599   
600   local ret_=""
601   "$service_path_" "$action_"
602   ret_=$?
603   if [[ $ret_ != 0 ]]; then
604     if [ -z "$message_" ]; then
605       "$error_function_" "Problems ${action_}ing service \"$service_\"" $ret_
606     else
607       "$error_function_" "$message_" $ret_
608     fi
609     return 1
610   fi
611   dprint "_touchService(): successfully started service \"$service_\""
612   return 0
613 }
614
615 function _createServiceFunctions
616 {
617   for i in "start" "stop" "restart" "reload" "force-reload"; do
618     eval "function ${i}Service { _touchService ${i} \"\$1\" \"\$2\" \"\$3\"; }"
619   done
620 }
621 _createServiceFunctions
622 # }}}
623
624 # prints the next free /dev/loop* to stdout
625 function findNextFreeLoop
626 {
627   local error_function_=${1:-"eprint"}    # function to call on error
628   local message_="$2"    # user supplied error message
629
630   local tmp_=''   # tmp
631   local i=''      # counter
632   local ret_=''   # saved return value
633   
634   for i in 'losetup' 'losetup.orig'; do
635     tmp_=`$i -f 2>/dev/null`
636     if [ $? -eq 0 ]; then
637       echo $tmp_
638       return 0
639     fi
640   done
641
642   # we have to search
643   dprint 'findNextFreeLoop(): losetup does not recognice option -f, searching next free loop device'
644   for i in `seq 0 100`; do
645     test -e /dev/loop$i || continue
646     losetup /dev/loop$i &>/dev/null
647     ret_=$?
648     case "$ret_" in
649       2) continue ;;  # losetup could not get status of loopdevice (EPERM)
650       0) continue ;;  # device exist
651       1) echo "/dev/loop$i"; return 0 ;;  # device does not exist and no error
652       ?) continue ;;  # return value not available in 'man losetup'
653     esac
654   done
655
656   # hmm... could not find a loopdevice
657   if [ -z "$message_" ]; then
658     $error_function_ "could not find a free loop device"
659   else
660     $error_function_ "$message_"
661   fi
662   return 1
663 }
664
665
666 # INIT {{{
667
668 function _initProgName
669 {
670   local name_="$1"    # program name
671   
672   local tmp_name_=`basename "$name_"` || \
673     logger -p user.alert -i "Init-initProgName: problems executing ( basename \"$name_\" ) ret($?)" >/dev/null
674   
675   secureInput "$tmp_name_"
676 }
677 PROG_NAME__=`_initProgName "$0"`
678
679
680 function _checkExecutables
681 {
682   local tmp_=""
683   for i in tr dirname basename id logger kill cat grep route awk ifconfig; do
684     type -p $i &>/dev/null || tmp_="${tmp_}$i "
685   done
686   if [ -n "$tmp_" ]; then
687     eprint "Init-checkExecutables: following executables not found or not executable:\n$tmp_"
688     #syslog "Init-checkExecutables: following executables not found or not executable: $tmp_"
689   fi
690 }
691 _checkExecutables
692
693
694 function _checkBootParam
695 {
696   local path_="/proc/cmdline"
697   if [ -e "$path_" ]; then
698     CMD_LINE__=`execute "cat $path_" warnLog`
699     return 0
700   fi
701   warnLog "$path_ does not exist, thus sh-lib may not work reliable!"
702   return 1
703 }
704 _checkBootParam
705
706
707 function _setDebugLevel
708 {
709   local debug_="${DEBUG:-0}"
710   VERBOSE__="$debug_"
711 }
712 _checkBootParam
713 # }}}
714
715 # END OF FILE
716 ################################################################################
717 # vim:foldmethod=marker expandtab shiftwidth=2 tabstop=2