84d45e0e1bd977f873394126119e6bd49d6a444f
[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   local abspath_=''
351
352   abspath_="`readlink -f \"$relpath_\"`" || \
353     warn "relToAbs(): Problems getting absolute path" "$?" || return 1
354   dprint "relToAbs(): \"$relpath_\" => \"$abspath_\""
355   echo "$abspath_"
356 }
357
358 # Simple shell grep
359 function stringInFile
360 {
361   local to_test_="$1"   # matching pattern
362   local source_="$2"    # source-file to grep
363
364   if [ ! -e "$source_" ]; then
365     eprint "stringInFile(): \"$source_\" does not exist"
366     return 1
367   fi
368
369   case "$(cat $source_)" in *$to_test_*) return 0;; esac
370   return 1
371 }
372
373 # same for strings
374 function stringInString
375 {
376   local to_test_="$1"   # matching pattern
377   local source_="$2"    # string to search in
378
379   case "$source_" in *$to_test_*) return 0;; esac
380   return 1
381 }
382
383 # get value for bootparam given as first param
384 function getBootParam
385 {
386   local param_to_search_="$1"
387   local result_=''
388
389   stringInString " $param_to_search_=" "$CMD_LINE__" || return 1
390   result_="${CMD_LINE__##*$param_to_search_=}"
391   result_="${result_%%[   ]*}"
392   echo "$result_"
393   return 0
394 }
395
396 # Check boot commandline for specified option
397 function checkBootParam
398 {
399   stringInString " $1" "$CMD_LINE__"
400   return "$?"
401 }
402
403
404 # NETWORK  {{{
405
406 # validates an IP FIXME
407 function netValidIp
408 {
409   local ip_="$1"    # ip addresse to validate
410   local error_function_=${2:-"eprint"}    # function to call on error
411   local message_="$3"    # user supplied error message
412   
413   local ret_=''
414
415   echo "$ip_" | grep -E -q -e '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}.[0-9]{1,3}' \
416     &>/dev/null
417   ret_=$?
418   if [ $ret_ -ne 0 ]; then
419     if [ -z "$message_" ]; then
420       "$error_function_" "ip-addresse \"$ip_\" is NOT valied" $ret_
421     else
422       "$error_function_" "$message_" $ret_
423     fi
424     return 1
425   fi
426
427   dprint "ip-addresse \"$ip_\" is valied" $ret_
428   return $ret_
429 }
430
431 function netGetIfaces
432 {
433   local error_function_=${1:-"eprint"}    # function to call on error
434   local message_="$2"    # user supplied error message
435   local if_=''
436   local ret_=''
437
438   #ip a|grep 'inet ' |awk '$NF !~ /lo/{print $NF}'
439   if_="`ip a|grep 'inet ' |awk '{print $NF}'`"
440   ret_=$?
441   if [ -z "$if_" ]; then
442     if [ -z "$message_" ]; then
443       "$error_function_" "no interfaces found" $ret_
444     else
445       "$error_function_" "$message_" $ret_
446     fi
447     return 1
448   fi
449   dprint "interfaces found" $ret_
450   echo "$if_"
451 }
452
453 # FIXME
454 function netGetDefaultGateway
455 {
456   local error_function_=${1:-"eprint"}    # function to call on error
457   local message_="$2"    # user supplied error message
458   
459   local ip_=''
460   local ret_=''
461   
462   setCLang
463   ip_=`route -n | awk '/^0\.0\.0\.0/{print $2; exit}'`
464   ret_=$?
465   restoreLang
466   if [ -z "$ip_" ]; then
467     if [ -z "$message_" ]; then
468       "$error_function_" "no default gateway found" $ret_
469     else
470       "$error_function_" "$message_" $ret_
471     fi
472     return 1
473   fi
474   dprint "default gateway is \"$ip_\"" $ret_
475   echo "$ip_"
476   return 0
477 }
478
479 # FIXME
480 function netGetNetmask
481 {
482   local iface_="$1"
483   local error_function_=${2:-"eprint"}    # function to call on error
484   local message_="$3"    # user supplied error message
485   
486   local nm_=''
487   local ret_=''
488   
489   setCLang
490   nm_=`ifconfig "$iface_" | awk '/[Mm]ask/{FS="[:   ]*"; $0=$0; print $8; exit}'`
491   ret_=$?
492   restoreLang
493   if [ -z "$nm_" ]; then
494     if [ -z "$message_" ]; then
495       "$error_function_" "could not find a netmask for \"$iface_\"" $ret_
496     else 
497       "$error_function_" "$message_" $ret_
498     fi
499     return 1
500   fi
501   dprint "netmask on \"$iface_\" is \"$nm_\"" $ret_
502   echo "$nm_"
503   return 0
504 }
505
506 # FIXME
507 function netGetIp
508 {
509   local iface_="$1"
510   local error_function_=${2:-"eprint"}    # function to call on error
511   local message_="$3"    # user supplied error message
512
513   local ip_=""
514   local ret_=""
515
516   setCLang
517   #ip_=`ip addr list eth0 |mawk '/inet/{split($2,A,"/"); print A[1]}'`
518   ip_=`ifconfig "$iface_" | awk '/[Ii]net [Aa]ddr/{FS="[:  ]*"; $0=$0; print $4; exit}'`
519   ret_=$?
520   restoreLang
521   if [ -z "$ip_" ]; then
522     if [ -z "$message_" ]; then
523       "$error_function_" "no ip for \"$iface_\" found" $ret_
524     else
525       "$error_function_" "$message_" $ret_
526     fi
527     return 1
528   fi
529   dprint "addresse for \"$iface_\" is \"$ip_\"" $ret_
530   echo "$ip_"
531   return 0
532
533
534 function netGetNameservers
535 {
536   local error_function_=${1:-"eprint"}    # function to call on error
537   local message_="$2"    # user supplied error message
538   
539   local file_="/etc/resolv.conf"
540   local ns_=""
541
542   if [ ! -e $file_ ]; then
543     warn "file \"$file_\" does not exist, could not get nameservers"
544     return 1
545   fi
546   
547   setCLang
548   ns_=`awk '/^nameserver/{printf "%s ",$2}' $file_`
549   restoreLang
550   if [ -z "$ns_" ]; then
551     if [ -z "$message_" ]; then
552       "$error_function_" "no nameservers found" $ret_
553     else
554       "$error_function_" "$message_" $ret_
555     fi
556     return 1
557   fi
558   dprint "nameservers: \"$ns_\"" $ret_
559   echo "$ns_"
560   return 0
561 }
562
563 # }}}
564
565 # SERVICES {{{
566 function _touchService
567 {
568   local action_="${1:-"start"}"
569   local service_="$2"
570   local error_function_=${3:-"eprint"}    # function to call on error
571   local message_="$4"     # user supplied error message
572
573   local i=""
574   local known_action_='false'
575   for i in "start" "stop" "restart" "reload" "force-reload"; do
576     if [[ $i == $action_ ]]; then
577       known_action_='true'
578       break
579     fi
580   done
581   $known_action_ || warn "_touchService(): unknown action \"$action_\""
582
583
584   local service_path_=""
585   service_path_="${INITD_DIR__}/$service_"
586   if [ ! -e "$service_path_" ]; then
587     warn "_touchService(): service does not exist: \"$service_\""
588     return 1
589   fi
590   if [ ! -x "$service_path_" ]; then
591     warn "_touchService(): service is not executable: \"$service_\""
592   fi
593   
594   local ret_=""
595   "$service_path_" "$action_"
596   ret_=$?
597   if [[ $ret_ != 0 ]]; then
598     if [ -z "$message_" ]; then
599       "$error_function_" "Problems ${action_}ing service \"$service_\"" $ret_
600     else
601       "$error_function_" "$message_" $ret_
602     fi
603     return 1
604   fi
605   dprint "_touchService(): successfully started service \"$service_\""
606   return 0
607 }
608
609 function _createServiceFunctions
610 {
611   for i in "start" "stop" "restart" "reload" "force-reload"; do
612     eval "function ${i}Service { _touchService ${i} \"\$1\" \"\$2\" \"\$3\"; }"
613   done
614 }
615 _createServiceFunctions
616 # }}}
617
618 # prints the next free /dev/loop* to stdout
619 function findNextFreeLoop
620 {
621   local error_function_=${1:-"eprint"}    # function to call on error
622   local message_="$2"    # user supplied error message
623
624   local tmp_=''   # tmp
625   local i=''      # counter
626   local ret_=''   # saved return value
627   
628   for i in 'losetup' 'losetup.orig'; do
629     tmp_=`$i -f 2>/dev/null`
630     if [ $? -eq 0 ]; then
631       echo $tmp_
632       return 0
633     fi
634   done
635
636   # we have to search
637   dprint 'findNextFreeLoop(): losetup does not recognice option -f, searching next free loop device'
638   for i in `seq 0 100`; do
639     test -e /dev/loop$i || continue
640     losetup /dev/loop$i &>/dev/null
641     ret_=$?
642     case "$ret_" in
643       2) continue ;;  # losetup could not get status of loopdevice (EPERM)
644       0) continue ;;  # device exist
645       1) echo "/dev/loop$i"; return 0 ;;  # device does not exist and no error
646       ?) continue ;;  # return value not available in 'man losetup'
647     esac
648   done
649
650   # hmm... could not find a loopdevice
651   if [ -z "$message_" ]; then
652     $error_function_ "could not find a free loop device"
653   else
654     $error_function_ "$message_"
655   fi
656   return 1
657 }
658
659
660 # INIT {{{
661
662 function _initProgName
663 {
664   local name_="$1"    # program name
665   
666   local tmp_name_=`basename "$name_"` || \
667     logger -p user.alert -i "Init-initProgName: problems executing ( basename \"$name_\" ) ret($?)" >/dev/null
668   
669   secureInput "$tmp_name_"
670 }
671 PROG_NAME__=`_initProgName "$0"`
672
673
674 function _checkExecutables
675 {
676   local tmp_=""
677   for i in tr dirname basename id logger kill cat grep route awk ifconfig; do
678     type -p $i &>/dev/null || tmp_="${tmp_}$i "
679   done
680   if [ -n "$tmp_" ]; then
681     eprint "Init-checkExecutables: following executables not found or not executable:\n$tmp_"
682     #syslog "Init-checkExecutables: following executables not found or not executable: $tmp_"
683   fi
684 }
685 _checkExecutables
686
687
688 function _checkBootParam
689 {
690   local path_="/proc/cmdline"
691   if [ -e "$path_" ]; then
692     CMD_LINE__=`execute "cat $path_" warnLog`
693     return 0
694   fi
695   warnLog "$path_ does not exist, thus sh-lib may not work reliable!"
696   return 1
697 }
698 _checkBootParam
699
700
701 function _setDebugLevel
702 {
703   local debug_="${DEBUG:-0}"
704   VERBOSE__="$debug_"
705 }
706 _checkBootParam
707 # }}}
708
709 # END OF FILE
710 ################################################################################
711 # vim:foldmethod=marker expandtab shiftwidth=2 tabstop=2