Added tag 1.02.11 for changeset 2012fa75db2414baff94dd39e3c414e22ffee341
[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 ##
181 # ATTENTION... THIS FUNCTINOS IS A BIG SECURITY HOLE
182 # this function will be changed in future release
183 ##
184 # i don't want to write exit status controle stuff every time
185 function execute
186 {
187   local to_exec_="$1"   # command to execute
188   local error_function_=${2:-"eprint"}    # function to call on error
189   local message_="$3"   # user supplied error message
190
191   local ret_=''
192
193   # NOT A GOOD IDEA
194   eval "$to_exec_"
195   ret_=$?
196
197   if [ $ret_ -eq 127 ]; then
198     syslog "problems executing ( $to_exec_ )" $ret_
199   fi
200   if [ $ret_ -ne 0 ]; then
201     if [ -z "$message_" ]; then
202       $error_function_ "problems executing ( $to_exec_ )" "$ret_"
203     else
204       $error_function_ "$message_" "$ret_"
205     fi
206   fi
207   dprint "exec-$error_function_: ( $to_exec_ ) ret($ret_)"
208   return $ret_
209 }
210
211 function silentExecute
212 {
213   unsetVerbose
214   execute "$@"
215   local ret_=$?
216   restoreVerbose
217   return $ret_
218 }
219
220
221 ###
222 #
223 # TEST FUNCTIONS
224 #
225 ###
226
227 # if the file DOES exist, everything is fine
228 function isExistent
229 {
230   local file_to_test_="$1"    # file to test
231   local error_function_=${2:-"eprint"}    # function to call on error
232   local message_="$3"    # user supplied error message
233
234   if [ ! -e "$file_to_test_" ]; then
235     if [ -z "$message_" ]; then
236       $error_function_ "file does not exist \"$file_to_test_\"" 66
237     else
238       $error_function_ "$message_"
239     fi
240     return 1
241   fi
242   dprint "isExistent(): file \"$1\" does exist => ready to go"
243   return 0
244 }
245
246 function isNotExistent
247 {
248   local file_to_test_="$1"    # file to test
249   local error_function_=${2:-"eprint"}    # function to call on error
250   local message_="$3"    # user supplied error message
251
252   if [ -e "$file_to_test_" ]; then
253     if [ -z "$message_" ]; then
254       $error_function_ "file does already exist \"$file_to_test_\"" 67
255     else
256       $error_function_ "$message_"
257     fi
258     return 1
259   fi
260   dprint "isNotExistent(): file \"$1\" does not exist => ready to go"
261   return 0
262 }
263
264
265 function checkUser
266 {
267   local to_check_="$1"    # username to check against running process
268   local error_function_=${2:-"eprint"}    # function to call on error
269   local message_="$3"    # user supplied error message
270
271   local user_=''
272
273   user_=`id -un`
274   if [ $user_ != "$to_check_" ]; then
275     if [ -z "$message_" ]; then
276       $error_function_ "username \"$user_\" is not \"$to_check_\"" 77 $exit_function_
277     else
278       $error_function_ "$message_"
279     fi
280     return 1
281   else
282     dprint "checkUser(): accepted, username matches \"$to_check_\""
283     return 0
284   fi
285 }
286
287 function checkId
288 {
289   local to_check_="$1"    # user-id to check against running process
290   local error_function_=${2:-"eprint"}    # function to call on error
291   local message_="$3"    # user supplied error message
292
293   local user_id_=''
294
295   user_id_=`id -u`
296   if [ $user_id_ != "$to_check_" ]; then
297     if [ -z "$message_" ]; then
298       $error_function_ "UID \"$user_id_\" is not \"$to_check_\"" 77
299     else
300       $error_function_ "$message_"
301     fi
302     return 1
303   else
304     dprint "checkId(): accepted, UID matches \"$to_check_\""
305     return 0
306   fi
307 }
308
309 function checkRoot
310 {
311   checkId 0 "$1" "$2"
312 }
313
314 function isGrml
315 {
316   if [ -f /etc/grml_version ] ; then 
317     dprint "isGrml(): this seems to be a grml system"
318     return 0                       
319   else                               
320     dprint "isGrml(): this is not a grml system"
321     return 1                       
322   fi                                 
323 }
324
325 function runsFromHd
326 {
327   if [ -e "/etc/grml_cd" ]; then
328     dprint "runsFromHd(): grml is on CD"
329     return 1
330   else
331     dprint "runsFromHd(): grml is on HD"
332     return 0
333   fi
334 }
335
336 function runsFromCd
337 {
338   if [ -e "/etc/grml_cd" ]; then
339     dprint "runsFromCd(): grml is on CD"
340     return 0
341   else
342     dprint "runsFromCd(): grml is on HD"
343     return 1
344   fi
345 }
346
347
348 # secure input from console
349 function secureInput
350 {
351   local to_secure_="$1"
352   
353   local secured_=''
354
355   secured_=`echo -n "$to_secure_" |tr -c '[:alnum:]/.\-,\(\)' '_'`
356   dprint "secureInput(): \"$to_secure_\" => \"$secured_\""
357   echo "$secured_"
358 }
359
360
361 # convert all possible path formats to absolute paths
362 function relToAbs
363 {
364   local relpath_="$1"
365   local abspath_=''
366
367   abspath_="`readlink -f \"$relpath_\"`" || \
368     warn "relToAbs(): Problems getting absolute path" "$?" || return 1
369   dprint "relToAbs(): \"$relpath_\" => \"$abspath_\""
370   echo "$abspath_"
371 }
372
373 # Simple shell grep
374 function stringInFile
375 {
376   local to_test_="$1"   # matching pattern
377   local source_="$2"    # source-file to grep
378
379   if [ ! -e "$source_" ]; then
380     eprint "stringInFile(): \"$source_\" does not exist"
381     return 1
382   fi
383
384   case "$(cat $source_)" in *$to_test_*) return 0;; esac
385   return 1
386 }
387
388 # same for strings
389 function stringInString
390 {
391   local to_test_="$1"   # matching pattern
392   local source_="$2"    # string to search in
393
394   case "$source_" in *$to_test_*) return 0;; esac
395   return 1
396 }
397
398 # get value for bootparam given as first param
399 function getBootParam
400 {
401   local param_to_search_="$1"
402   local result_=''
403
404   stringInString " $param_to_search_=" "$CMD_LINE__" || return 1
405   result_="${CMD_LINE__##*$param_to_search_=}"
406   result_="${result_%%[   ]*}"
407   echo "$result_"
408   return 0
409 }
410
411 # Check boot commandline for specified option
412 function checkBootParam
413 {
414   stringInString " $1" "$CMD_LINE__"
415   return "$?"
416 }
417
418
419 # NETWORK  {{{
420
421 # validates an IP FIXME
422 function netValidIp
423 {
424   local ip_="$1"    # ip addresse to validate
425   local error_function_=${2:-"eprint"}    # function to call on error
426   local message_="$3"    # user supplied error message
427   
428   local ret_=''
429
430   echo "$ip_" | grep -E -q -e '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}.[0-9]{1,3}' \
431     &>/dev/null
432   ret_=$?
433   if [ $ret_ -ne 0 ]; then
434     if [ -z "$message_" ]; then
435       "$error_function_" "ip-addresse \"$ip_\" is NOT valied" $ret_
436     else
437       "$error_function_" "$message_" $ret_
438     fi
439     return 1
440   fi
441
442   dprint "ip-addresse \"$ip_\" is valied" $ret_
443   return $ret_
444 }
445
446 function netGetIfaces
447 {
448   local error_function_=${1:-"eprint"}    # function to call on error
449   local message_="$2"    # user supplied error message
450   local if_=''
451   local ret_=''
452
453   #ip a|grep 'inet ' |awk '$NF !~ /lo/{print $NF}'
454   if_="`ip a|grep 'inet ' |awk '{print $NF}'`"
455   ret_=$?
456   if [ -z "$if_" ]; then
457     if [ -z "$message_" ]; then
458       "$error_function_" "no interfaces found" $ret_
459     else
460       "$error_function_" "$message_" $ret_
461     fi
462     return 1
463   fi
464   dprint "interfaces found" $ret_
465   echo "$if_"
466 }
467
468 # FIXME
469 function netGetDefaultGateway
470 {
471   local error_function_=${1:-"eprint"}    # function to call on error
472   local message_="$2"    # user supplied error message
473   
474   local ip_=''
475   local ret_=''
476   
477   setCLang
478   ip_=`route -n | awk '/^0\.0\.0\.0/{print $2; exit}'`
479   ret_=$?
480   restoreLang
481   if [ -z "$ip_" ]; then
482     if [ -z "$message_" ]; then
483       "$error_function_" "no default gateway found" $ret_
484     else
485       "$error_function_" "$message_" $ret_
486     fi
487     return 1
488   fi
489   dprint "default gateway is \"$ip_\"" $ret_
490   echo "$ip_"
491   return 0
492 }
493
494 # FIXME
495 function netGetNetmask
496 {
497   local iface_="$1"
498   local error_function_=${2:-"eprint"}    # function to call on error
499   local message_="$3"    # user supplied error message
500   
501   local nm_=''
502   local ret_=''
503   
504   setCLang
505   nm_=`ifconfig "$iface_" | awk '/[Mm]ask/{FS="[:   ]*"; $0=$0; print $8; exit}'`
506   ret_=$?
507   restoreLang
508   if [ -z "$nm_" ]; then
509     if [ -z "$message_" ]; then
510       "$error_function_" "could not find a netmask for \"$iface_\"" $ret_
511     else 
512       "$error_function_" "$message_" $ret_
513     fi
514     return 1
515   fi
516   dprint "netmask on \"$iface_\" is \"$nm_\"" $ret_
517   echo "$nm_"
518   return 0
519 }
520
521 # FIXME
522 function netGetIp
523 {
524   local iface_="$1"
525   local error_function_=${2:-"eprint"}    # function to call on error
526   local message_="$3"    # user supplied error message
527
528   local ip_=""
529   local ret_=""
530
531   setCLang
532   #ip_=`ip addr list eth0 |mawk '/inet/{split($2,A,"/"); print A[1]}'`
533   ip_=`ifconfig "$iface_" | awk '/[Ii]net [Aa]ddr/{FS="[:  ]*"; $0=$0; print $4; exit}'`
534   ret_=$?
535   restoreLang
536   if [ -z "$ip_" ]; then
537     if [ -z "$message_" ]; then
538       "$error_function_" "no ip for \"$iface_\" found" $ret_
539     else
540       "$error_function_" "$message_" $ret_
541     fi
542     return 1
543   fi
544   dprint "addresse for \"$iface_\" is \"$ip_\"" $ret_
545   echo "$ip_"
546   return 0
547
548
549 function netGetNameservers
550 {
551   local error_function_=${1:-"eprint"}    # function to call on error
552   local message_="$2"    # user supplied error message
553   
554   local file_="/etc/resolv.conf"
555   local ns_=""
556
557   if [ ! -e $file_ ]; then
558     warn "file \"$file_\" does not exist, could not get nameservers"
559     return 1
560   fi
561   
562   setCLang
563   ns_=`awk '/^nameserver/{printf "%s ",$2}' $file_ |xargs echo`
564   restoreLang
565   if [ -z "$ns_" ]; then
566     if [ -z "$message_" ]; then
567       "$error_function_" "no nameservers found" $ret_
568     else
569       "$error_function_" "$message_" $ret_
570     fi
571     return 1
572   fi
573   dprint "nameservers: \"$ns_\"" $ret_
574   echo "$ns_"
575   return 0
576 }
577
578 # }}}
579
580 # SERVICES {{{
581 function _touchService
582 {
583   local action_="${1:-"start"}"
584   local service_="$2"
585   local error_function_=${3:-"eprint"}    # function to call on error
586   local message_="$4"     # user supplied error message
587
588   local i=""
589   local known_action_='false'
590   for i in "start" "stop" "restart" "reload" "force-reload"; do
591     if [[ $i == $action_ ]]; then
592       known_action_='true'
593       break
594     fi
595   done
596   $known_action_ || warn "_touchService(): unknown action \"$action_\""
597
598
599   local service_path_=""
600   service_path_="${INITD_DIR__}/$service_"
601   if [ ! -e "$service_path_" ]; then
602     warn "_touchService(): service does not exist: \"$service_\""
603     return 1
604   fi
605   if [ ! -x "$service_path_" ]; then
606     warn "_touchService(): service is not executable: \"$service_\""
607   fi
608   
609   local ret_=""
610   "$service_path_" "$action_"
611   ret_=$?
612   if [[ $ret_ != 0 ]]; then
613     if [ -z "$message_" ]; then
614       "$error_function_" "Problems ${action_}ing service \"$service_\"" $ret_
615     else
616       "$error_function_" "$message_" $ret_
617     fi
618     return 1
619   fi
620   dprint "_touchService(): successfully started service \"$service_\""
621   return 0
622 }
623
624 function _createServiceFunctions
625 {
626   for i in "start" "stop" "restart" "reload"; do
627     eval "function ${i}Service { _touchService ${i} \"\$1\" \"\$2\" \"\$3\"; }"
628   done
629   eval "function forceReloadService { _touchService force-reload \"\$1\" \"\$2\" \"\$3\"; }"
630 }
631 _createServiceFunctions
632 # }}}
633
634 # prints the next free /dev/loop* to stdout
635 function findNextFreeLoop
636 {
637   local error_function_=${1:-"eprint"}    # function to call on error
638   local message_="$2"    # user supplied error message
639
640   local tmp_=''   # tmp
641   local i=''      # counter
642   local ret_=''   # saved return value
643   
644   for i in 'losetup' 'losetup.orig'; do
645     tmp_=`$i -f 2>/dev/null`
646     if [ $? -eq 0 ]; then
647       echo $tmp_
648       return 0
649     fi
650   done
651
652   # we have to search
653   dprint 'findNextFreeLoop(): losetup does not recognice option -f, searching next free loop device'
654   for i in `seq 0 100`; do
655     test -e /dev/loop$i || continue
656     losetup /dev/loop$i &>/dev/null
657     ret_=$?
658     case "$ret_" in
659       2) continue ;;  # losetup could not get status of loopdevice (EPERM)
660       0) continue ;;  # device exist
661       1) echo "/dev/loop$i"; return 0 ;;  # device does not exist and no error
662       ?) continue ;;  # return value not available in 'man losetup'
663     esac
664   done
665
666   # hmm... could not find a loopdevice
667   if [ -z "$message_" ]; then
668     $error_function_ "could not find a free loop device"
669   else
670     $error_function_ "$message_"
671   fi
672   return 1
673 }
674
675
676 # INIT {{{
677
678 function _initProgName
679 {
680   local name_="$1"    # program name
681   
682   local tmp_name_=`basename "$name_"` || \
683     logger -p user.alert -i "Init-initProgName: problems executing ( basename \"$name_\" ) ret($?)" >/dev/null
684   
685   secureInput "$tmp_name_"
686 }
687 PROG_NAME__=`_initProgName "$0"`
688
689
690 function _checkExecutables
691 {
692   local tmp_=""
693   for i in tr dirname basename id logger kill cat grep route awk ifconfig; do
694     type -p $i &>/dev/null || tmp_="${tmp_}$i "
695   done
696   if [ -n "$tmp_" ]; then
697     eprint "Init-checkExecutables: following executables not found or not executable:\n$tmp_"
698     #syslog "Init-checkExecutables: following executables not found or not executable: $tmp_"
699   fi
700 }
701 _checkExecutables
702
703
704 function _checkBootParam
705 {
706   local path_="/proc/cmdline"
707   if [ -e "$path_" ]; then
708     CMD_LINE__=`execute "cat $path_" warnLog`
709     return 0
710   fi
711   warnLog "$path_ does not exist, thus sh-lib may not work reliable!"
712   return 1
713 }
714 _checkBootParam
715
716
717 function _setDebugLevel
718 {
719   local debug_="${DEBUG:-0}"
720   VERBOSE__="$debug_"
721 }
722 _setDebugLevel
723 # }}}
724
725 # END OF FILE
726 ################################################################################
727 # vim:foldmethod=marker expandtab shiftwidth=2 tabstop=2